在C中使用++运算符对语句进行短路评估 [英] Short circuit evaluation of a statement with ++ operator in C
问题描述
我已经在Windows 7的Code :: Blocks 10.05中执行了以下代码.
I have executed the following code in Code::Blocks 10.05 on Windows 7.
int a=0,b=0,c;
c=a++&&b++;
printf("\na=%d\nb=%d\nc=%d\n\n",a,b,c);
我获得的输出如下,
a=1
b=0
c=0
由于具有短路评估功能,因此这很合理.
This makes perfect sense because of short circuit evaluation.
表达式a++
是后递增,并且0
返回到逻辑和(&&
).因此,部分b++
未被评估,因为0 && 0
和
0 && 1
评估为0
.
The expression a++
is post increment and 0
is returned to the logical and (&&
). Hence the part b++
is not evaluated since both 0 && 0
and
0 && 1
evaluates to 0
.
但我对此表示怀疑.运算符的优先级值明确指出++
的优先级高于&&
.所以我的理解是这样的,对a++
和b ++都进行了评估,然后&&
仅检查表达式a++
的结果来做出决定.但这并没有发生,仅在此处评估a++
.
But here arises my doubt. The precedence value of operators clearly states that ++
is having higher precedence over &&
. So my understanding was like this, both a++
and b++ are evaluated and then &&
only checks the result of expression a++
to come to a decision. But this has not happened only a++
is evaluated here.
此行为的原因是什么? &&
作为序列点是否与此行为有关?如果是这样,为什么我们说&&
的优先级低于++
?
What is the reason for this behavior? Does &&
being a sequence point has something to do with this behavior? If so why we say that &&
is having lower precedence than ++
?
推荐答案
您对优先级和评估顺序感到困惑.
优先级定义了运算符的分组方式,即
Precedence defines how the operators are grouped, i.e
c = a++ && b++;
等效于:
c = ((a++) && (b++));
求值顺序定义了表达式的求值方式,&&
的短路表示a++
首先求值,如果为零,则结束;如果它不为零,则对b++
求值.
Order of evaluation defines how the expression is evaluated, the short circuit of &&
means a++
is evaluated first, if it's zero, the end; if it's not zero, b++
is then evaluated.
另一个例子:
c = (a++) + (b++);
在b++
之前评估了a++
吗?答案是我们不知道.大多数运算符不定义评估顺序. &&
是很少定义的运算符之一. (其余为||
,,
和?:
)
Is a++
evaluated before b++
? The answer is we don't know. Most operators don't define the order of evaluation. &&
is one of the few operators that do define. (The rest are ||
, ,
and ?:
)
这篇关于在C中使用++运算符对语句进行短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!