[英]Associativity and Sequence Points in C
Since the associativity of '?' 由于“?”的关联性 is from right to left,any 2 consecutive '?'
是从右到左,连续2个? 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
在语句中,x的值为0,表达式为
int y= x? 0 : 1;
hence i expected y to be 1,but it shows Zero on my dev-cpp.Where am i wrong? 因此我期望y为1,但在我的dev-cpp上显示为零。我在哪里错?
You have the order of evaluation wrong. 您的评估顺序有误。 In
a ? b : c
在
a ? b : c
a ? b : c
, a
is always evaluated first, then either b
or c
is evaluated. a ? b : c
, a
总是先进行计算,然后或者b
或c
进行评价。
I've marked up your example so that I can identify subexpressions: 我已经标记了您的示例,以便可以标识子表达式:
c
int y=x?x++?x:-1:1;
a bbbbbbbb
(a) is evaluated, yielding -1, so (b) is evaluated. (a)被评估为-1,所以(b)被评估。 There,
x++
is evaluated, yielding -1 again, so (c) is evaluated. 在那里,对
x++
进行了评估,再次得出-1,因此对(c)进行了评估。 At this point, x
is 0. 此时,
x
为0。
Or, with more verbose, clearer code, it's as if you said: 或者,用更冗长,更清晰的代码,就像您说的那样:
int x = -1;
int y;
if (x != 0)
{
int new_x = x + 1;
if (x != 0)
{
y = new_x;
}
else
{
y = -1;
}
}
else
{
y = 1;
}
Operations: 操作方式:
Assign y to value =
if(x): --> x = -1, so true as it is non-zero
{
if(x): --> x = -1 ,so true as x will increment later due to post increment
x= x +1; --> increment x, so x = 0 . This is the value assigned. So y = 0;
else:
-1
}
else:
{
1
}
Hope this helps! 希望这可以帮助!
The answer to your question is that in C/C++ int y = x ? (x++?x:-1) : 1;
您的问题的答案是在C / C ++中
int y = x ? (x++?x:-1) : 1;
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. 从左。
x=-1; (Actual Value)
x=-1; (Value used in expression)
y=-1?(x++?x:-1):1;
Second sequence point is second ?
第二个顺序点是第二个
?
from left. 从左。 As mentioned above the update operations are effective after sequence so even though
x++
is there the value used in this sequence is -1
and updated value will be used in following. 如上所述,更新操作在序列之后是有效的,因此即使存在
x++
,该序列中使用的值为-1
,下面将使用更新的值。
x=0; (Actual Value, bcoz of x++)
x=-1; (Value used in expression)
y=-1?x:-1;
Now it will be 现在它将
x=0; (Actual Value)
x=0; (Value used in expression)
y=x;
y=0;
Hope this make sense now. 希望这现在有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.