Gcc "overflow in expression" while equivalent equivalent expression works fine
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 compilation conclusion
# 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 I see this warning and different results? if 36 can fit in char, then 36 ^ 8 can fit in unsigned long long int, so I'm not sure if this is a problem, please report. (I am using gcc 4.9.2)
static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36); 36 is of type int
∴ 36 * 36 is of type int
∴ (36 * 36 * 36 * 36) is of type int
∴ (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36) is of type int and overflow, which is actually undefined for signed types.
You probably wanted
static const unsigned long long int xx = (36ull * 36 * 36 * 36) * (36 * 36 * 36 * 36); Regarding the second case:
static const unsigned long long int yy = y * y; y is of type unsigned long long
∴ y * y is of type unsigned long long , so there is no overflow.