Safe integer overflows in C++

Ian Lance Taylor iant@google.com
Thu Apr 14 19:32:00 GMT 2011


Piotr Wyderski <piotr.wyderski@gmail.com> writes:

> However, signed overflows are considered UB in C and C++, so my library
> doesn't need to be portable beyond the "sane" platform set -- U2, 2^n encodings
> with 32- and 64-bit fundamental types. I know that GCC does a lot to detect
> overflow-related errors, as they are mostly bugs. But in this case I
> know exactly
> what's happening under the hood, so assuming the above caveats, the question
> is how to perform overflowing integral arithmetic in GCC more or less
> safely, e.g.:
>
> std::int64_t x = ..., y = ...;
> std::int64_t z = x + y; // may overflow!
>
> if (overflow) {
>
>     // enter slow correction path
>
> } else {
>
>     // fast path
> }
>
> and how to detect that addition/subtraction has overflowed.
> Are there any pragmas or built-ins related to the above issue?
>
> As a last resort I can use GCC inline assembly, but since the set of
> target platforms is relatively big (x86, x86, SPARC, POWER, Itanium),
> I'd rather want to use a semi-portable gnu++0x-based solution.

You could consider using unsigned types.

Or, restricting yourself to gcc, the simplest option would to use the
-fwrapv option.  With -fwrapv gcc defines signed overflow to wrap using
twos-complement arithmetic.  That will let you reliably detect overflow.

Without using -fwrapv or -fno-strict-overflow, there is no way in gcc to
reliably detect signed overflow after it occurs.  The only thing you can
do is check before the operation whether it will occur.

Ian



More information about the Gcc-help mailing list