I was working with integers in C, trying to explore more on when and how overflow happens.
I noticed that when I added two positive numbers, the sum of which overflows, I always got a negative number.
On the other hand, if I added two negative numbers, the sum of which overflows, I always got a positive number (including 0).
I made few experiments, but I would like to know if this is true for every case.
Best Answer
Integer overflows are undefined behavior in C.
C says an expression involving integers overflows, if its result after the usual arithmetic conversions is of a signed typed and cannot be represented in the type of the result. Assignment and cast expressions are an exception as they are ruled by the integer conversions.
Expressions of unsigned type cannot overflow; they wrap, e.g.,
0U - 1
isUINT_MAX
.Examples:
Never let any integer expression overflow; modern compilers (like
gcc
) take advantage of integer overflows being undefined behavior to perform various types of optimizations.For example:
when
a
is of typeint
after promotion, the expression is reduced ingcc
(when optimization is enabled) to:It takes advantage of the expression being undefined behavior when
a
is in the rangeINT_MIN + 10 - 1
toINT_MIN
.This optimization could not be done when
a
isunsigned int
because ifa
is0
, thena - 10
has to be evaluated asUINT_MAX - 9
(no undefined behavior). Optimizinga - 10 < 20
toa < 30
would then lead to a different result than the required one whena
is0
to9
.