Allowing signed integer overflows in C/C++

Signed overflow is undefined in C, and that’s for real.

One solution follows:

signed_result = (unsigned int)one_argument + (unsigned int)other_argument;

The above solution involves implementation-defined behavior in the final conversion from unsigned to int but do not invoke undefined behavior. With most compilation platforms’ implementation-defined choices, the result is exactly the two’s complement result that you expect.

Finally, an optimizing compiler for one of the numerous platforms on which implementation-defined choices force the compiler to give you the behavior you expect will compile the above code to the obvious assembly instruction.

Alternately, if you are using gcc, then the options -fwrapv/-fno-strict-overflow may be exactly what you want. They provide an additional guarantee with respect to the standard that signed overflows wrap around. I’m not sure about the difference between the two.

Leave a Comment