c - C 条件语句中的 "And"和 "Or"运算符

标签 c optimization logical-operators evaluation logical-and

我总是想知道一些事情,但在其他地方找不到答案。如果我有这段代码:

if ((cond1) &&(cond2) && (cond 3) && (cond 4))
 {
       // do something
 }

假设第一个条件为假,那么我的程序也会验证其他条件,或者只是跳过验证它们?

但是如果我有

if ((cond1) ||(cond2) || (cond 3) || (cond 4))
 {
       // do something
 }

并且条件 1 为真,我的程序会立即执行 if 部分还是继续验证其他条件?

最佳答案

引用 C11 标准,第 §6.5.13 章,逻辑 AND 运算符(强调我的)

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.

关于c - C 条件语句中的 "And"和 "Or"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285861/

相关文章:

javascript - 当按位运算符做同样的事情时为什么要使用逻辑运算符?

c++ - 关于优先顺序(c++)

C 自由和结构

java - 优化 arrayRotateLeft 方法

arrays - 玩转matlab

javascript - 如果脚本确实很短,那么使用内联 JavaScript 是否优于外部包含?

c - 为什么我需要在同名的 .c 文件中包含一个 .h 头文件?

c -/usr/local/lib 中的子文件夹?

C编程: EXC_BAD_ACCESS