c=a+++b 运算是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7485088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the operation c=a+++b mean?
提问by user595985
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?
我预计输出为 3,5,8,主要是因为 a++ 表示 2 +1 等于 3,而 3 + 5 等于 8,所以我预计为 3,5,8。结果是3,5,7。有人可以解释为什么会这样吗?
回答by Fred Foo
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
.
它被解析为c = a++ + b
,a++
表示后增量,即取值a
计算后的增量a + b == 2 + 5
。
Please, neverwrite code like this.
请不要写这样的代码。
回答by Nawaz
Maximal Munch Ruleapplies 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
。
回答by David
a++ is postincrementing, i.e. the expression takes the value of a and thenadds 1.
c = ++a + b would do what you expect.
a++ 是后递增,即表达式取 a 的值然后加1。
c = ++a + b 会做你期望的。
回答by Stefano
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
to的当前值b
和之后的增量相加a
!
回答by Patrick87
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++ 在表达式中计算 a 的值后更改 a 的 tge 值。由于 a 的原始值是 2,这就是用于计算 c 的值;在计算 ++ 后, a 的值会更改以反映新值。
回答by Aman Agarwal
a++ + b ..it gives the result 7 and after the expression value of a is update to 3 because of the post increment operator
a++ + b ..它给出了结果 7 并且在 a 的表达式值更新为 3 之后,因为后增量运算符
回答by jrok
a++ gets evaluated after the expression.
a++ 在表达式之后求值。
c = ++a + b; would give you what you thought.
c = ++a + b; 会给你你的想法。
回答by Vineet G
According to Longest Matchrule it is parsed as a++ + +b during lexical analysis phase of compiler. Hence the resultant output.
根据最长匹配规则,它在编译器的词法分析阶段被解析为 a++ + +b。因此产生的输出。
回答by Alok Negi
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.
这里 c= a+++b; 表示 c= (a++) +b;即岗位增量。在 a++ 中,更改将在打印 a、b 和 c 的下一步中发生。在 ++a 中,即前缀递增,更改将发生在同一步骤中,并且输出为 8。