Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc "overflow in expression" while equivalent equivalent expression works fine

Tags:

c++

gcc

c++11

Here is my code

#include <iostream>
static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);
static const unsigned long long int y = 36 * 36 * 36 * 36;
static const unsigned long long int yy = y * y;

int main()
{
  std::cout << xx << std::endl;
  std::cout << yy << std::endl;
  return 0;
}

This the compilation output

# g++ -std=c++11 test.cpp -o test
test.cpp:2:62: warning: integer overflow in expression [-Woverflow]
 static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);

This is the execution output

# ./test
18446744073025945600
2821109907456

Can you explain why do I see this warning and different results? if 36 can fit into char then 36^8 can fit in unsigned long long int so I'm not sure what is problem here, please advise. (I'm using gcc 4.9.2)

like image 357
e271p314 Avatar asked May 19 '16 08:05

e271p314


1 Answers

static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);

36 has type int

36 * 36 has type int

(36 * 36 * 36 * 36) has type int

(36 * 36 * 36 * 36) * (36 * 36 * 36 * 36) has type int and overflows, which is actually undefined behavior for signed types.

You probably wanted

static const unsigned long long int xx = (36ull * 36 * 36 * 36) * (36 * 36 * 36 * 36);

As for the second case:

static const unsigned long long int yy = y * y;

y has type unsigned long long

y * y has type unsigned long long so there's no overflow.

like image 73
user657267 Avatar answered Oct 11 '22 18:10

user657267