c++ - How do promotion rules work when the signedness on either side of a binary operator differ? -
consider following programs:
// http://ideone.com/4i0dt #include <limits> #include <iostream> int main() { int max = std::numeric_limits<int>::max(); unsigned int 1 = 1; unsigned int result = max + one; std::cout << result; } and
// http://ideone.com/ubufz #include <limits> #include <iostream> int main() { unsigned int = 42; int neg = -43; int result = + neg; std::cout << result; } how + operator "know" correct type return? general rule convert of arguments widest type, here there's no clear "winner" between int , unsigned int. in first case, unsigned int must being chosen result of operator+, because result of 2147483648. in second case, must choosing int, because result of -1. yet don't see in general case how decidable. undefined behavior i'm seeing or else?
this outlined explicitly in §5/9:
many binary operators expect operands of arithmetic or enumeration type cause conversions , yield result types in similar way. purpose yield common type, type of result. pattern called usual arithmetic conversions, defined follows:
- if either operand of type
long double, other shall convertedlong double.- otherwise, if either operand
double, other shall converteddouble.- otherwise, if either operand
float, other shall convertedfloat.- otherwise, integral promotions shall performed on both operands.
- then, if either operand
unsigned longother shall convertedunsigned long.- otherwise, if 1 operand
long int, otherunsigned int, iflong intcan represent values ofunsigned int,unsigned intshall convertedlong int; otherwise both operands shall convertedunsigned long int.- otherwise, if either operand
long, other shall convertedlong.- otherwise, if either operand
unsigned, other shall convertedunsigned.[note: otherwise, remaining case both operands
int]
in both of scenarios, result of operator+ unsigned. consequently, second scenario effectively:
int result = static_cast<int>(us + static_cast<unsigned>(neg)); because in case value of us + neg not representable int, value of result implementation-defined – §4.7/3:
if destination type signed, value unchanged if can represented in destination type (and bit-field width); otherwise, value implementation-defined.
Comments
Post a Comment