Thursday, July 9, 2009

Operator precedence in C Language?

Hi,


This might be a small program for you folks, but here it is. I have a doubt what exactly is being processed (which Operator is acting on which operand(s) ? )in each "pass" when the statement m=++i+j++; is executed in the below program.





int m,i=5,j=5;


m=++i+j++;


printf("%d",m);

Operator precedence in C Language?
m = ++i + j++;





steps, in order:


1) i is incremented


2) i and j are added and the result is stored in m


3) j is incremented.





As a rule of thumb, ++x increments x before the value is used in any way. x++ increments x after it is used.





so,


y = ++x; //means y = x + 1, and x = x + 1


y = x++; //means y = x, and x = x + 1
Reply:The answer is 6+5=11.





++i increments i to 6 and then uses 6 in the calculation.





j++ will use 5 in the calculation and then increment it to 6


No comments:

Post a Comment