How to detect 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 value-added. So for 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.

There are other ways to achieve this but they provide estimates only. You can check them out here −

Updated on 24-Jun-2020 06:01:55