C integer overflow behaviour when assigning to larger-width integers

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

    Both operands are promoted to int32_t during the subtraction. If the result had been larger than the maximum value for int32_t you would've seen overflow.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 07:54

    The short answer is that these are all promoted to int during the subtraction. For the long answer, look at section 6.3.1.1 of the C standard, where it talks about integer promotions in arithmetic expressions. Relevant language from the standard:

    If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

    The details are in there, too, but they get pretty nasty.

    0 讨论(0)
提交回复
热议问题