我很好奇 C 标准关于条件子句中变量赋值的确切定义。这是一个小例子:
int foo() {
...
}
int bar() {
...
}
int main () {
int a, b, x, y;
...
if ( (a = foo()) == x && (b = bar() == y ) {
...
}
...
}
GCC 的测试表明,如果 (a = foo()) != x
, b = bar()
不会被执行。一方面,这种行为是最佳的,因为它不会在 bar()
的计算上浪费任何时间。 。但另一方面, b
的值有点未定义,因为它取决于 foo()
的结果,实际上与 b
无关.
我想知道 C 标准中是否有针对此类情况的明确定义以及该定义的原因是什么。最后,编写此类代码的最佳实践是什么?
最佳答案
A test with GCC revealed that if (a = foo()) != x, b = bar() will not be executed.
嗯,这是逻辑 AND (&&
) 运算符的属性。
引用 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.
也就是说,对于 b
的赋值,你是对的,如果第一个操作数为 FALSE,则 b
的值保持不变不确定并且该变量的任何使用都可能导致 undefined behavior .
(其中之一)最佳实践是在定义时初始化局部变量,以避免使用不确定的值。
关于c - && 之后的条件变量赋值 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46726618/