C integer overflow behaviour when assigning to larger-width integers

后端 未结 4 2031
攒了一身酷
攒了一身酷 2021-01-05 07:32

If I execute the following code in C:

#include 

uint16_t a = 4000;
uint16_t b = 8000;

int32_t c = a - b;

printf(\"%d\", c);
4条回答
  •  天涯浪人
    2021-01-05 07:51

    There is, in fact, an overflow but C does not tell you.

    The overflow leaves a value that happens to be -4000 when interpreted as a signed integer. This works as designed on 2's complement machines.

    Try to interpret the result as unsigned, and you'll notice that (u1-u2) evaluates to some seemingly unrelated number when u1 < u2.

提交回复
热议问题