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