Unsigned integer overflow is well defined by both the C and C++ standards. For example, the C99 standard (§6.2.5/9
) states
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
However, both standards state that signed integer overflow is undefined behavior. Again, from the C99 standard (§3.4.3/1
)
An example of undefined behavior is the behavior on integer overflow
Is there an historical or (even better!) a technical reason for this discrepancy?
if (a + b < a)
) too. Overflow on multiplication is hard for both signed and unsigned types. – hvd Aug 12 '13 at 20:10MAX_INT+1 == -0
, while on a two's complement it would beINT_MIN
– David Rodríguez - dribeas Aug 12 '13 at 20:11