Unexpected Results from Signed/Unsigned Integer Overflow
In C , integer overflow can lead to unexpected results depending on the signedness of the data type.
Consider the following program:
#include <iostream> int main() { int x(0); std::cout << x << std::endl; x = x + 2147483647; std::cout << x << std::endl; x = x + 1; std::cout << x << std::endl; std::cout << std::endl; unsigned int y(0); std::cout << y << std::endl; y = y + 4294967295; std::cout << y << std::endl; y = y + 1; std::cout << y << std::endl; }
The output of this program may surprise you:
0 2147483647 -2147483648 0 4294967295 0
Explanation
For signed integers, overflow behavior is undefined. In most implementations, 2's complement is used, which leads to unexpected wrapping-around behavior. For instance, in the program above:
For unsigned integers, overflow is well-defined and wraps around modulo 2bits. In other words, the value is reset to 0 when overflowing the maximum. This explains the output for y, where y wraps around to 0 after overflowing the maximum unsigned value, 4294967295.
It's important to note that the behavior for signed integer overflow is not guaranteed by the language and may vary depending on the implementation and machine architecture. Therefore, it's generally not recommended to rely on such behavior in your programs.
The above is the detailed content of Why does integer overflow in C lead to different results for signed and unsigned integers?. For more information, please follow other related articles on the PHP Chinese website!