Search code examples
c++c++11bitwise-operators

Why do 1ll << i does give us correct answer but not long long i ; 1<<i?


Since 1 operand in << operator is of long long type, and the answer should be stored as long long, I am a little surprised by this behavior can anyone explain why this happens?
For Example:

   #include<bits/stdc++.h>
   using namespace std;

   int main(){
       long long p=33;
       long long a = 1<<p;
       cout<<a;

   }   //This gives the wrong output
   
    int main(){

       long long a = 1ll<<33;
       cout<<a;

    } //this gives right output

Solution

  • C++11 (N3690) 5.8 Shift operators [expr.shift] p1:

    The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand.

    So the type of 1 << i is int, whereas 1LL << i has type long long, which can usually represent a greater range of values.

    The shift operators are exceptional here; most other operators follow the usual arithmetic conversions [5 p10], which cause both operands to be converted to the same type, roughly speaking the larger of the two.