C integer overflow behaviour when assigning to larger-width integers

后端 未结 4 2032
攒了一身酷
攒了一身酷 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:53

    The issue is actually somewhat complicated. Operands of arithmetic expressions are converted using specific rules that you can see in Section 3.2.1.5 of the Standard (C89). In your case, the answer depends on what the type uint16_t is. If it is smaller than int, say short int, then the operands are converted to int and you get -4000, but on a 16-bit system, uint16_t could be unsigned int and conversion to a signed type would not happen automatically.

提交回复
热议问题