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

2019-01-04 03:35发布

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?

标签: c++ c visual-c++
9条回答
SAY GOODBYE
2楼-- · 2019-01-04 03:40

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-04 03:40

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.

查看更多
别忘想泡老子
4楼-- · 2019-01-04 03:48

a++ + b ..it gives the result 7 and after the expression value of a is update to 3 because of the post increment operator

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-04 03:55

According to Longest Match rule it is parsed as a++ + +b during lexical analysis phase of compiler. Hence the resultant output.

查看更多
We Are One
6楼-- · 2019-01-04 03:56

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!

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-04 03:57

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.

查看更多
登录 后发表回答