How to detect overflow during arithmetic operations?
When adding two numbers a and b.
- If both a and b are positive, if the result of the addition is smaller than a (or b), the overflow happened.
- If both a and b are negative, if the result of the addition is greater than a (or b), the underflow happened.
- If two numbers have different sign, it won't overflow or underflow.
Answer #2 : gcc builtin function
Most CPUs have overflow and underflow flag get set in case of such situation happen. It is very easy for assembly code to detect these flags, but not for codes written in high level language. It may try to insert inline assembly code that checks CPU flags, but there is no guarantee that the flag was set because of the operation that the programmer was interested in; the compiler may insert other arithmetic to calculate the location of the memory it wants to access, or may reorder codes.
So for this purpose, gcc provides many builtin-functions such as __builtin_add_overflow() or __builtin_mul_overflow(). For the full list of functions, please refer to GCC manual.