gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:56:06 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com