Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 answer should be stored as long long
I am little surprised with 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 wrong output
   
    int main(){

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

    } //this gives right output

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading