I ran the following two pieces of code on Windows XP (Code:Block, MinGW), and Ubuntu (11.04, G++)
I have trouble running the following code
#include <iostream>
using namespace std;
int main(){
long long a = 9223372036854775807;
cout << a;
return 0;
}
That number is 2^63 -1. But I will get an error stating:
C:\Documents and Settings\JohnWong\My Documents\codeblock\343_hw_1\main.cpp|9|error: integer constant is too large for "long" type|
On ubuntu - it compiled, but the answer retunred is 9223372036854775808, notice the 8 at the end....
Now if I run this code, using the power function, I am okay.
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main(){
long long a = pow(2,64);
cout << "a: " << setprecision(20) << a << endl;
开发者_StackOverflow社区 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 cause an overflow, that's okay).
On Ubuntu the outputs looks the same. Good.
So what's going on here? Why constant is not good??? I even tried intmax_t and int64_t as datatype running the first code.
Can someone explain this behavior? Thanks!
long long a = 9223372036854775807LL;
The LL makes the literal a long long literal. Otherwise the literal defaults to being a long literal and then is casted over to a long long before being stored in a.
C++ language did not have long long
type before C++11. Your compiler is apparently not a C++11 compiler, and it supports long long
as an extension. This is why the compiler issues the warning. It warns you that the literal is interpreted in a non-standard (extended) way, i.e. that while searching for the appropriate type for the literal, the compiler had to go outside the bounds of the language standard.
精彩评论