Friday, May 21, 2010

C language expression?

s=++a + a++ + --a + a--;(a=10)





its answer is 40 how.





why a is not ++a =11 or --a =9. explain it .

C language expression?
S=40, a=10 after execution of the step





Explanation:





rules:


1) post fix ++ and -- have more precedence than prefix ++ and --.


2) postfix ++ and -- have associativity from left to right.


3) Prefix ++ and -- have associativity from right to left.


4) + has the lowest precedence among them all





now lets call the terms ++a as t1


a++ as t2


--a as t3


a-- as t4.


So the expression is t1+t2+t3+t4, right?


now


the evaluation will be done in this order


1) t2 (because of rule 1 and 2)


t2=a++ and a =10 so after execution t2=10 and s=11





note: i hope u know that a postfix ++ assigns the value first and then increments the variable, ie


for x=3,


s=x++ will do this, assign the value of x(3) to s and then increment x so s becomes 3 and x becomes 4.


prefix ++ and -- increment or decrement the value first and then assign it .








2) t4 (because of rule 1 and 2) so t4=11, a=10





3) t3 (because of rule 3) so t3=9, a=9





4) t1 (because of rule 3) so t1=10, a=10








in the end t1+t2+t3+t4 = 10+10+9+11 = 40 and a =10
Reply:posfix expression has more preceedence rather then prefix,


so postfix is solved first,


that is why ++a is not equal to 11 as a++=11 and then ++a=12
Reply:this is how i understand it.


+ has more precedence over ++ and -- so, a+a is evaluated first.


in both the cases and therefore it becomes 20+20 = 40.


i have to admit that it isnt very clear.
Reply:see it goes like this


s=++a+a+++--a+a--


so, s=++10+10+++--10+10--


therefore,++=+


+-=+,so cancle those two+%26amp;-


so u get only +


then +10


and then the last -- means +; ie --=+


therefore,s=+10+10+10+10


s=40


it is not nessary to put the last +sign.


i hope u got it


good luck
Reply:its a wrong answer
Reply:yaa


++a= 11


a++=10


--a=9


a--=10





so 11+10+9+10=40





C execute and save its value after whole expression


No comments:

Post a Comment