Check for Integer Overflow in C++

C++Server Side ProgrammingProgramming

The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either values added. So for example,

Example

unsigned int x, y;
unsigned int value = x + y;
bool overflow = value < x; // Alternatively "value < y" should also work

This is because if x and y are both unsigned ints, if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values.

Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.

Published on 25-Sep-2019 13:50:37