Search code examples
cinteger-overflow

long ans = ((long) INT_MIN) * 2 - 1; causing a warning because of integer overflow


I have this in my code and it is causing the warning that follows:

long ans = ((long) INT_MIN) * 2 - 1;  

The warning that I get is:

warning: integer overflow detected: op "*"

I have included limits.h so that I could use INT_MIN

#include <limits.h>

Solution

  • This means that the calculation will overflow the range of long. Signed overflow yields undefined behavior.

    The only correlation between the range of values representable by long and the value INT_MIN is that INT_MIN is representable as a long. There is no guarantee that one less than twice INT_MIN is representable as a long.