开发者

What does the operation c=a+++b mean?

The following code has me confused

int a=2,b=5,c;
c=a+++b;
printf("%d,%d,%d",a,b,c);

I expe开发者_如何学运维cted 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?


It's parsed as c = a++ + b, and a++ means post-increment, i.e. increment after taking the value of a to compute a + b == 2 + 5.

Please, never write code like this.


Maximal Munch Rule applies to such expression, according to which, the expression is parsed as:

c = a++ + b;

That is, a is post-incremented (a++) and so the current value of a (before post-increment) is taken for + operation with b.


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.


This is an example of bad programming style.

It is quite unreadable, however it post increments a so it sums the current value of a to b and afterwards increments a!


a++ gets evaluated after the expression.

c = ++a + b; would give you what you thought.


The post increment operator, a++, changes tge value of a after the value of a is evaluated in the expression. Since the original value of a is 2, that's what's used to compute c; the value of a is changed to reflect the new value after the ++ is evaluated.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜