文章出處

Usual Arithmetic Conversion: The integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
 
I extract out some fragments  of C99 standard to explain the integer promotions are performed on both operands.
 example:
 1     #include <stdlib.h>
 2     #include <stdio.h>
 3     #define PRINT_COMPARE_RESULT(a, b) \
 4         if (a > b) { \
 5             printf( #a " > " #b "\n"); \
 6         } \
 7         else if (a < b) { \
 8             printf( #a " < " #b "\n"); \
 9         } \
10         else { \
11             printf( #a " = " #b "\n" ); \
12         }
13 
14     int main()
15     {
16         int a = -1;
17         unsigned short b = 2;
18         unsigned int c = 2;
19 
20         PRINT_COMPARE_RESULT(a,b);
21         PRINT_COMPARE_RESULT(a,c);
22 
23         return 0;
24     }


The result is a > c and a < b.

Operands a that has signed integer type has rank less than the rank of the type of the operand c,so the a with signed integer type is converted the type of the c with unsigned integer type.The signed integer -1 is coverted to unsigned integer is 0xffffffff that is greater than the value 3 of unsigned integer c.However, the rank of a is greater than the rank of b that has unsigned short integer type,so the unsigned short integer type is converted to signed int type.So a < b.

 

 

 
 

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()