c - && 之后的条件变量赋值 (C)

标签 c conditional-statements variable-assignment

我很好奇 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/

相关文章:

c - 使用气体时符号名称冲突

c - 为什么下面给我一个从 double *** 到 const double*** 的转换错误

python - python-pandas中通过 bool 运算符获取数字索引

ruby-on-rails - Rails - 有条件地记录特定主机名

unit-testing - Clojure : Determine if a variable is declared

python-3.x - 赋值操作Python

c - 你如何使用 wait() 杀死僵尸进程

c++ - gcc 版本之间的舍入差异

php - 如果每次循环后提交语句都没有通过

javascript - 将 json 分配给变量