Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence while using right and left shift operators

I want to know how the output of following C program is 32. Please provide me a step by step guidance on the same.

main()
{
    int a=4,b=2;
    a=b<<a+b>>2;
    printf("%d",a);
}
like image 457
hanish Avatar asked Jun 16 '26 23:06

hanish


2 Answers

Asking about precedence, + has higher precedence than << and >>, so the expression is

b << (a + b) >> 2

evaluated as

2 << (4 + 2) >> 2 = 2 << 6 >> 2

Now, there's again to decide which part is evaluated first -- << and >> have the same precedence, but associativity comes to the rescue, for << and >> it is left-to-right, so this means the leftmost operator is evaluated first:

(2 << 6) >> 2 = 128 >> 2 = 32

edit: doing all in one step, respecting precedence and associativity, your original expression b<<a+b>>2 reads the following fully parenthesized:

((b << (a + b)) >> 2

For future doubts, it's very helpful to have a table showing both precedence and associativity. Or just use some "superfluous" parenthesis to make the expression more readable to humans ;)

int a=4,b=2;
a=b<<a+b>>2;

Here b is 2 == (0000 0000 0010)

a = 2<<(4+2)>>2; // as ADD(+) is having higher precedence so first we will solve addtion.
a = 2 << 6 >> 2;

a = ((2 << 6) >> 2); //<<  >>, Associativity (left-to-right) so first solve (2 << 6).

Shifting 6 bits to left

After solving 2<<6  (0000 1000 0000)  == 128  
                          ^^^^ ^^   <-- left  

Shifting 2 bits to right

Now 128>>2  (0000 0010 0000)  == 32.  
        Right -->  ^^
like image 36
Himanshu Avatar answered Jun 19 '26 18:06

Himanshu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!