Saturday, March 3, 2018

Precedence and associativity of operators

Recently at a meetup, one of my colleagues asked the following question:  
int a =1; int b=2; c=a+++b;
What is the value of c?
SOLUTION: So for the answer, you need to look at precedence and associativity of operators here ++ has higher priority than + and will be evaluated first. Therefore, the equation is equivalent to
c= (a++)+b;   //(1++)+2=1+2=3
And the value of c is 3.  

Lets take another example. Suppose we add the line
c=a=b;
to the above code. Now what is the value of c?
SOLUTION: Both the operators (=) are of the same precedence. Therefore associativity comes into the picture and the associativity of = is from right to left. Therefoer, the equation is equivalent to,
 c=(a=b);
And the value of c is 2  

TIP: You can memorize the basic structure of the precedence table using the following trick: PUMASRELCA  - each letter is the first letter of each category in the table arranged in order. Let me take you to the animal kingdom: PUMA S(low) R(red) E(lephants) L(loath) C(at) A(udio)    

No comments:

Post a Comment