Integral Promotion

bool foo() 
{
    unsigned int a = 6;  
    int b = -20;        // If 'b' is 'long long'?

    return a + b < 6 ? true : false;
 }

  If 'int b = -20;', the result is false, because 'a + b' => (unsigned + int) => (unsigned + unsigned) in integral promotion. Thus result is unsigned(-14), that's say, 4294967282.
  But, if 'long long b = -20;', the result is true! Since 'a + b' => (unsigned + long long) => (long long + long long), thus result is long long(-14).

Let's see the definition of integral promotion.

"A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer maybe used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion."

 

Thank 剪澜碎影 for the question.

 

posted @ 2013-02-19 17:57  walfud  阅读(290)  评论(0编辑  收藏  举报