Signed overflow is undefined. Unsigned overflow wraps. Implementing signed wraparound arithmetic is mostly a matter of doing everything in unsigned math. There are a few things to be careful about, though:
unsigned short
andunsigned char
arithmetic works by converting the operands to eitherint
orunsigned int
first. Usuallyint
, unless you’re on a weird setup whereint
doesn’t have enough range to store allunsigned short
values. That means that convertingshort
orchar
tounsigned short
orunsigned char
for arithmetic can still produce signed integer overflow and UB. You need to do your math inunsigned int
or larger to avoid this.- unsigned->signed conversion is technically implementation-defined when the original value is beyond the range of the result type. This shouldn’t be a problem on most compilers and architectures.
Alternatively, if you want to go the compiler flag route, -fwrapv
makes signed overflow wrap for addition, subtraction, and multiplication on GCC and Clang. It doesn’t do anything about INT_MIN / -1
, though.
0
solved Implementing / enforcing wraparound arithmetic in C [closed]