Can the type difference between constants 32768 and 0x8000 make a difference?

后端 未结 5 1896
攒了一身酷
攒了一身酷 2021-01-04 04:30

The Standard specifies that hexadecimal constants like 0x8000 (larger than fits in a signed integer) are unsigned (just like octal constants), whereas decimal constants like

5条回答
  •  时光说笑
    2021-01-04 05:10

    Yes, it can matter. If your processor has a 16-bit int and a 32-bit long type, 32768 has the type long (since 32767 is the largest positive value fitting in a signed 16-bit int), whereas 0x8000 (since it is also considered for unsigned int) still fits in a 16-bit unsigned int.

    Now consider the following program:

    int main(int argc, char *argv[])
    {
      volatile long long_dec = ((long)~32768);
      volatile long long_hex = ((long)~0x8000);
    
      return 0;
    }
    

    When 32768 is considered long, the negation will invert 32 bits, resulting in a representation 0xFFFF7FFF with type long; the cast is superfluous. When 0x8000 is considered unsigned int, the negation will invert 16 bits, resulting in a representation 0x7FFF with type unsigned int; the cast will then zero-extend to a long value of 0x00007FFF. Look at H&S5, section 2.7.1 page 24ff.

    It is best to augment the constants with U, UL or L as appropriate.

提交回复
热议问题