Which data type to use for a very large numbers in C++?

Vaibhav picture Vaibhav · Aug 29, 2010 · Viewed 23.4k times · Source

I have to store the number 600851475143 in my program. I tried to store it in long long int variable and long double as well but on compiling it shows the error

integer constant is too large for "long" type. 

I have also tried unsigned long long int too. I am using MinGW 5.1.6 for running g++ on windows.

What datatype should I use to store the number?

Answer

Peter Alexander picture Peter Alexander · Aug 29, 2010

long long is fine, but you have to use a suffix on the literal.

long long x = 600851475143ll; // can use LL instead if you prefer.

If you leave the ll off the end of the literal, then the compiler assumes that you want it to be an int, which in most cases is a 32-bit signed number. 32-bits aren't enough to store that large value, hence the warning. By adding the ll, you signify to the compiler that the literal should be interpreted as a long long, which is big enough to store the value.

The suffix is also useful for specifying which overload to call for a function. For example:

void foo(long long x) {}
void foo(int x) {}

int main()
{
    foo(0); // calls foo(int x)
    foo(0LL); // calls foo(long long x)
}