Harish Patil
Harish Patil

Reputation: 65

Impact of precedence of bit manipulation operator on output

I am running simple programe in visual studio 2008. which is giving 2 results as below. Please help me knowing why in first case it is giving result =1024 case 1:

#include<windows.h>
#include<iostream>

using namespace std;

int main()
{
    int i =4;
    k = i<<3 + i<<1;
    cout<<"Result "<<k;

    return 0;
}

output is 1024

case2:
    int j=0;
    j=i<<3;
    int n = i<<1;
    k = j+ n;
    cout<<"Result "<<k;

Output is 40

Upvotes: 0

Views: 57

Answers (1)

KIIV
KIIV

Reputation: 3739

It's all about the operator precedences:

i = 4;
k = i << 3 + i << 1;
// is the same expression as: 
k = (4 << (3 + 4)) << 1;

so 4 << (3+4) = 512 and 512 << 1 = 1024

Upvotes: 4

Related Questions