Holding 2 ^ 63 -1 in long long

I ran the following two codes on Windows XP (Code: Block, MinGW) and Ubuntu (11.04, g ++)

I am having trouble running the following code

#include <iostream> using namespace std; int main(){ long long a = 9223372036854775807; cout << a; return 0; } 

This number is 2 ^ 63 -1. But I get an error message:

C: \ Documents and Settings \ JohnWong \ My Documents \ codeblock \ 343_hw_1 \ main.cpp | 9 | error: integer constant is also large for the "long" type |

On ubuntu - it compiled, but the retunred answer is 9223372036854775808, note 8 at the end ....

Now, if I run this code using the power function, I'm fine.

 #include <iostream> #include <iomanip> #include <math.h> using namespace std; int main(){ long long a = pow(2,64); cout << "a: " << setprecision(20) << a << endl; cout << "a-1: " << setprecision(20) << a-1 << endl; cout << "a-2: " << setprecision(20) << a-2 << endl; cout << "a+0: " << setprecision(20) << a+0 << endl; cout << "a+1: " << setprecision(20) << a+1 << endl; cout << "a+2: " << setprecision(20) << a+2 << endl; cout << "a+3: " << setprecision(20) << a+3 << endl; return 0; } 

I will get the values ​​I want (anything from +1 will lead to overflow, which is good).

On Ubuntu, the outputs look the same. Good.

So what is going on here? Why is a constant not good ??? I even tried intmax_t and int64_t as the data type that runs the first code.

Can someone explain this behavior? Thank you

+8
c ++
source share
2 answers
 long long a = 9223372036854775807LL; 

LL makes a literal a long long literal. Otherwise, the default literal will be a long literal, and then passed for a long long period before being stored in.

+13
source share

The C ++ language did not have a long long type until C ++ 11. Your compiler, apparently, is not a C ++ 11 compiler and supports long long as an extension. This is why the compiler generates a warning. It warns you that the literal is interpreted in a non-standard (extended) way, that is, when searching for the appropriate type for the literal, the compiler must go beyond the standard language.

+2
source share

All Articles