Suppose
long long b = 5*1024*1024*1024; // 5 gigs, small enough for 64 bits
printf ("%lu\n",sizeof(long long)); // prints 8 (bytes) = 64 bits
but the compiler complains:
warning: integer overflow in expression [-Woverflow]
Why does it overflow, what am I missing?
An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
Integer overflow occurs when you try to express a number that is larger than the largest number the integer type can handle. If you try to express the number 300 in one byte, you have an integer overflow (maximum is 255). 100,000 in two bytes is also an integer overflow (65,535 is the maximum).
The C++ Language Specification simply states that the size of a long must be at least the size of an int . It used to be standard to have int = 2 bytes and long = 4 bytes.
Because the numbers on the right hand side are of type int
, not long long
, so int
arithmetic is performed in the expression, leading to an overflow.
If you add LL
to one of them, it'll promote them all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With