12

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Dervin Thunk
  • 19,515
  • 28
  • 127
  • 217

1 Answers1

20

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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
teppic
  • 8,039
  • 2
  • 24
  • 37
  • darn, you're right. One always thinks of appending f or (casting) floats... but never longs :( Appreciate it. – Dervin Thunk Apr 12 '13 at 00:07
  • @DervinThunk - it's easy to forget with constants. – teppic Apr 12 '13 at 00:19
  • 1
    More precisely, the constants are of type `int` ("integer" is a more general term, covering everything from `char` to `long long` and possibly more). And if you apply the `LL` to the right-most `1024`, you could still get an overflow; given `5*1024*1024*1024LL`, `5*1024*1024` is still evaluated as an `int` -- which can legally be as narrow as 16 bits. The most robust solution is probably to write `5LL*1024LL*1024LL*1024LL` -- or `5LL * (1LL<<30)`. – Keith Thompson Apr 12 '13 at 00:30
  • 1
    @KeithThompson ... or just `5LL<<30`. – Ruslan Feb 26 '21 at 08:17