Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are the results of integer promotion different?
    primarykey
    data
    text
    <p>Please look at my test code:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #define PRINT_COMPARE_RESULT(a, b) \ if (a &gt; b) { \ printf( #a " &gt; " #b "\n"); \ } \ else if (a &lt; b) { \ printf( #a " &lt; " #b "\n"); \ } \ else { \ printf( #a " = " #b "\n" ); \ } int main() { signed int a = -1; unsigned int b = 2; signed short c = -1; unsigned short d = 2; PRINT_COMPARE_RESULT(a,b); PRINT_COMPARE_RESULT(c,d); return 0; } </code></pre> <p>The result is the following:</p> <pre><code>a &gt; b c &lt; d </code></pre> <p>My platform is Linux, and my gcc version is 4.4.2. I am surprised by the second line of output. The first line of output is caused by integer promotion. But why is the result of the second line different?</p> <p>The following rules are from C99 standard:</p> <blockquote> <p>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.</p> <p>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 to the type of the operand with unsigned integer type.</p> <p>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.</p> <p>Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.</p> </blockquote> <p>I think both of the two comparisons should belong to the same case, the second case of integer promotion. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload