Difference in behaviour of unsigned and signed integer when integer overflow occurs [closed]-Collection of common programming errors
The primary rationale for the difference is the fact that C and C++ language specification allows the implementation to use one of the following three different signed integer representations
- 1’s complement
- 2’s complement
- Signed magnitude
If the language specification mandated some specific behavior in case of signed overflow (i.e. favored one of the above representations over the other two), it would force platforms based on two non-favored representations to implement “heavy” signed integer arithmetic. It would become necessary, since the natural machine-level behavior of such platforms would not match the behavior required by the language standard. These implementation would have to constantly watch for signed overflow and adjust the results to match the standard requirements.
That would severely degrade the performance of signed integer arithmetic on platforms that use non-favored signed representations, which is, of course, completely unacceptable in such languages as C and C++, which are designed to be as close as possible to the underlying hardware when it comes to such basic operations as integer arithmetic.
The reason the behavior is undefined (as opposed to *unspecified”) is because there are platforms out there which deliberately generate hardware exceptions in case of signed overflow during integer arithmetic. Note, that the behavior is undefined only for arithmetic operations, which are typically performed by the machine. For value conversions signed overflow does not produce undefined behavior (the behavior is actually implementation-defined).
As for unsigned types, they are represented identically on all platforms, which means that requiring consistent behavior across all platforms is not a problem. The wraparound that conceptually matches the “modulo 2^width” behavior is the natural behavior on virtually all known binary hardware platforms.
Originally posted 2013-11-10 00:08:47.