C 中的关联性和序列点
由于 '?' 的结合性从右到左,任意2个连续的'?'运营商一定要这样对待,对吧?
现在,
int x=-1;
int y=x?x++?x:-1:1;
我希望它的执行方式为:
int y = x ? (x++?x:-1) : 1;
现在,由于它是从右到左执行的,所以当遇到第一个“?”时在语句中,x 的值为 0,表达式如下,
int y= x? 0 : 1;
因此我期望 y 为 1,但它在我的 dev-cpp 上显示为零。我哪里错了?
Since the associativity of '?' is from right to left,any 2 consecutive '?' operators must be treated as such,Right?
Now,
int x=-1;
int y=x?x++?x:-1:1;
I expect this to be executed as:
int y = x ? (x++?x:-1) : 1;
Now since its being executed from right to left,when encountering the first '?' in the statement,x's value is 0 and the expression is as
int y= x? 0 : 1;
hence i expected y to be 1,but it shows Zero on my dev-cpp.Where am i wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的评估顺序错误。在
中? b : c
,a
始终首先计算,然后计算b
或c
。我已经标记了您的示例,以便我可以识别子表达式:
(a) 被求值,产生 -1,因此 (b) 被求值。在那里,
x++
被求值,再次产生 -1,因此 (c) 被求值。此时,x
为 0。或者,使用更详细、更清晰的代码,就好像您说:
You have the order of evaluation wrong. In
a ? b : c
,a
is always evaluated first, then eitherb
orc
is evaluated.I've marked up your example so that I can identify subexpressions:
(a) is evaluated, yielding -1, so (b) is evaluated. There,
x++
is evaluated, yielding -1 again, so (c) is evaluated. At this point,x
is 0.Or, with more verbose, clearer code, it's as if you said:
操作:
希望这有帮助!
Operations:
Hope this helps!
你的问题的答案是在 C/C++
int y = x ? (x++?x:-1) : 1;
我们将在?
处命中两个序列点。对序列点中的变量进行的任何更新操作将在该序列结束后生效。让我们看看我们手头的例子。第一个序列点是左起第一个
?
。第二个序列点是左起第二个
?
。如上所述,更新操作在序列之后有效,因此即使存在x++
,该序列中使用的值也是-1
并且更新后的值将在下面使用。现在希望
这现在有意义。
The answer to your question is that in C/C++
int y = x ? (x++?x:-1) : 1;
we will hit two sequence points at?
. Any update operations to variable with in a sequence point will be effective after that sequence is over. So lets look at our example in hand.First sequence point is first
?
from left.Second sequence point is second
?
from left. As mentioned above the update operations are effective after sequence so even thoughx++
is there the value used in this sequence is-1
and updated value will be used in following.Now it will be
Hope this make sense now.