Search code examples
c++initializationoverflowwarningslong-long

How would I set a long long to a huge number without a warning?


Right now, I have

long long x = 1 << 60;
cout << x << endl;

and I know that the range for long long can be all the way up to 2^64, but for some reason when I execute the piece of code, it gives me a warning that says "left shift count >= width of type [-Wshift-count-overflow]."

In addition, 0 is printed to the screen, which is obviously not what I wanted.

I tried putting the literal "ll" after it, but I don't know where I should put it:

long long x = (1 << 60)ll;
long long x = (1 << 60ll);

and none of them work

Could anyone please tell me how to fix this? Thanks in advance!


Solution

  • It is a common mistake to expect for this expression:

    long long x = 1 << 60;
    

    that type of left side would affect calculations on the right side. It is not, result of 1 << 60 converted to type on the left, but it does not affect calculation of 1 << 60 itself. So proper solution is to change type of 1:

    long long x = static_cast<long long >( 1 ) << 60;
    

    or

    long long x = 1LL << 60;
    

    or even

    auto x = 1LL << 60;