Unsigned Overflow in C

非 Y 不嫁゛ 提交于 2019-12-05 17:11:40

No, C types are subject to default promotions. Assuming uint16_t has lower conversion rank than int, it will be promoted to int and the addition will be carried out as an int, then converted to uint32_t when returned.

As for your related question at the end, I don't quite follow what you want.

Use a coding style that does not use compiler intermediaries for calculations, note that (1) is going to have the data type int.

uint32_t inc(uint16_t x) {
 uint16_t y = x + 1;
 return y;
}

A peculiarity of the way the standard describes integer overflow is that it allows compilers to assume that an overflow cannot occur. In the case you show there, the compiler is not expected to preserve the behavior of an overflow, since after all, the range of possible values that x+1 may take (assuming that overflow doesn't exist) fit in the return type.

For your second question, in C there is no such thing as overflow for unsigned types, the applicable term is wrapping. By definition unsigned types are computed modulo 2^width. Whenever you cast a wider unsigned type to one that is narrower the upper bits will simply be thrown away. All C compilers should implement it like this, there is nothing you have to worry about.

In essence unsigned types are quite simple, the nasty things only come for signed types.

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