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 converted long double.
  • otherwise, if either operand double, other shall converted double.
  • otherwise, if either operand float, other shall converted float.
  • otherwise, integral promotions shall performed on both operands.
  • then, if either operand unsigned long other shall converted unsigned long.
  • otherwise, if 1 operand long int , other unsigned int, if long int can represent values of unsigned int, unsigned int shall converted long int; otherwise both operands shall converted unsigned long int.
  • otherwise, if either operand long, other shall converted long.
  • otherwise, if either operand unsigned, other shall converted unsigned.

[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

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -