[英]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 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. 我期望输出为3,5,8,主要是因为a ++的意思是2 +1等于3,而3 + 5等于8,所以我期望3,5,8。 It turns out that the result is 3,5,7. 原来结果是3,5,7。 Can someone explain why this is the case? 有人可以解释为什么会这样吗?
It's parsed as c = a++ + b
, and a++
means post-increment, ie increment after taking the value of a
to compute a + b == 2 + 5
. 它的分析为c = a++ + b
,和a++
装置后增量,取的值后,即增量a
来计算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
是后递增( a++
)等的当前值a
(前后增量)被取为+
与操作b
。
a++ is post incrementing, ie the expression takes the value of a and then adds 1. a ++是后递增的,即表达式使用a的值, 然后加 1。
c = ++a + b would do what you expect. c = ++ a + b可以满足您的期望。
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
所以总结的当前值a
到b
,之后增加a
!
a++ gets evaluated after the expression. 在表达式之后对a ++求值。
c = ++a + b; 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. 在表达式中计算a的值后,后递增运算符a ++更改a的tge值。 Since the original value of a is 2, that's what's used to compute c; 由于a的原始值为2,因此用于计算c。 the value of a is changed to reflect the new value after the ++ is evaluated. 在评估++之后,更改a的值以反映新值。
a ++ + b ..it给出结果7,由于后置增量运算符,a的表达式值更新为3之后
According to Longest Match rule it is parsed as a++ + +b during lexical analysis phase of compiler. 根据最长匹配规则,在编译器的词法分析阶段将其解析为a ++ + + b。 Hence the resultant output. 因此,结果输出。
Here c= a+++b; 这里c = a +++ b; means c= (a++) +b; 表示c =(a ++)+ b; ie post increment. 即发布增量。 In a++, changes will occur in the next step in which it is printing a, b and c. 在a ++中,将在下一步打印a,b和c时进行更改。 In ++a, ie prefix-increment the changes will occur in the same step and it will give an output of 8. 在++ a中,即前缀递增,更改将在同一步骤中发生,并且输出为8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.