The following code has me confused
int a=2,b=5,c;
c=a+++b;
printf("%d,%d,%d",a,b,c);
I expected the output to be 3,5,8, mainly because a++ means 2 +1 which equals 3, and 3 + 5 equals 8, so I expected 3,5,8. It turns out that the result is 3,5,7. Can someone explain why this is the case?
a++ is post incrementing, i.e. the expression takes the value of a and then adds 1.
c = ++a + b would do what you expect.
Here c= a+++b; means c= (a++) +b; i.e post increment. In a++, changes will occur in the next step in which it is printing a, b and c. In ++a, i.e prefix-increment the changes will occur in the same step and it will give an output of 8.
a++ + b ..it gives the result 7 and after the expression value of a is update to 3 because of the post increment operator
According to Longest Match rule it is parsed as a++ + +b during lexical analysis phase of compiler. Hence the resultant output.
This is an example of bad programming style.
It is quite unreadable, however it post increments
a
so it sums the current value ofa
tob
and afterwards incrementsa
!It's parsed as
c = a++ + b
, anda++
means post-increment, i.e. increment after taking the value ofa
to computea + b == 2 + 5
.Please, never write code like this.