warning c4307 integral constant overflow in C

Makuvex Linux picture Makuvex Linux · Feb 1, 2014 · Viewed 8.9k times · Source

I have this operation (8 * (512 * 786432)) and the product is 3221225472

I tried to use it with variables like longlong, unsigned long

But the compiler throw me an error

c4307 integral constant overflow

and I need the result for use it with functions, how can I fix it? or what variables can work for large numbers?

regards

Answer

Dietrich Epp picture Dietrich Epp · Feb 1, 2014

The expression (8 * (512 * 786432)) has type int and it will overflow on 32-bit systems. Assigning it to a variable of type long does not change the fact that the value has already overflowed. You can fix this by annotating the numbers.

long x = (8L * (512L * 786432L));

You only need to put the L on one of the numbers, since it will force results to also have type long.

This assumes that long is 64-bit, which is true on most systems but not Windows. You will need LL (or i64) on Windows.