Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long long is 8 bytes, but I get integer overflow?

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?

like image 618
Dervin Thunk Avatar asked Apr 12 '13 00:04

Dervin Thunk


People also ask

What causes integer overflow?

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).

What is the integer overflow limit?

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).

Why is long int 4 bytes?

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.


1 Answers

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.

like image 170
teppic Avatar answered Nov 03 '22 09:11

teppic