C 中条件语句中的 "And" 和 "Or" 运算符
"And" and "Or" operators in conditionals in C
我总是想知道一些事情,但在别处找不到答案。如果我有这段代码:
if ((cond1) &&(cond2) && (cond 3) && (cond 4))
{
// do something
}
假设第一个条件为假,那么我的程序也会验证其他条件,或者只是跳过验证它们?
但是如果我有
if ((cond1) ||(cond2) || (cond 3) || (cond 4))
{
// do something
}
条件 1 为真,我的程序会立即进入 if 部分还是继续验证其他条件?
在 C 语言中 && 和 || "sort-circuit",意思是如果左操作数的评估足以确定结果,则不评估右操作数。
引用C11
标准,章节§6.5.13,逻辑与运算符(强调我的)
Unlike the bitwise binary &
operator, the &&
operator guarantees left-to-right evaluation;
if the second operand is evaluated, there is a sequence point between the evaluations of
the first and second operands. If the first operand compares equal to 0, the second
operand is not evaluated.
因此,如果第一个条件(LHS 操作数)的计算结果为 false,则后面的条件,即 &&
的 RHS 操作数为 未评价。
类似地(讽刺的是),对于逻辑"OR"运算符,
Unlike the bitwise |
operator, the ||
operator guarantees left-to-right evaluation; if the
second operand is evaluated, there is a sequence point between the evaluations of the first
and second operands. If the first operand compares unequal to 0, the second operand is
not evaluated.
我总是想知道一些事情,但在别处找不到答案。如果我有这段代码:
if ((cond1) &&(cond2) && (cond 3) && (cond 4))
{
// do something
}
假设第一个条件为假,那么我的程序也会验证其他条件,或者只是跳过验证它们?
但是如果我有
if ((cond1) ||(cond2) || (cond 3) || (cond 4))
{
// do something
}
条件 1 为真,我的程序会立即进入 if 部分还是继续验证其他条件?
在 C 语言中 && 和 || "sort-circuit",意思是如果左操作数的评估足以确定结果,则不评估右操作数。
引用C11
标准,章节§6.5.13,逻辑与运算符(强调我的)
Unlike the bitwise binary
&
operator, the&&
operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.
因此,如果第一个条件(LHS 操作数)的计算结果为 false,则后面的条件,即 &&
的 RHS 操作数为 未评价。
类似地(讽刺的是),对于逻辑"OR"运算符,
Unlike the bitwise
|
operator, the||
operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.