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;
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!
Maximum value of long long int in C++ Last Updated : 18 Dec, 2020 In this article, we will discuss the long long int data type in C++. long long int data type in C++ is used to store 64-bit integers. It is one of the largest data types to store integer values, unlike unsigned long long int both positive as well as negative.
A maximum integer value that can be stored in a long long int data type is typically 9, 223, 372, 036, 854, 775, 807 around 263 – 1 (but is compiler dependent). The maximum value that can be stored in long long int is stored as a constant in <climits> header file.
Some properties of the long long int data type are: Being a signed data type, it can store positive values as well as negative values. Takes a size of 64 bits where 1 bit is used to store the sign of the integer.
Edit: As johannes pointed out, long is 32 bits in Windows. I'm not sure this can be done portably in C++03 while still maintaining full standards compliance. long long and int64_t are not a part of the C++03 standard, but are offered as compiler extensions by the common compilers. Show activity on this post.
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.
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