C integer overflow behaviour when assigning to larger-width integers

天大地大妈咪最大 提交于 2019-11-30 20:35:49
TrayMan

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!