"a += a" 是未定义的行为,例如 "i = i++"?

Is "a += a" an undifined behaviour such as "i = i++"?

我了解到 i = i++ 是 C 中的未定义行为。但我对 a += a 有疑问。这也是未定义的行为吗?

不,a += a 不是未定义的。由于 C 2018 6.5 2 中的这条规则,i = i++ 的行为未由 C 标准定义:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

该规则适用,因为 i++i = 都有更新 i 的副作用,并且它们没有排序。 (虽然 i++ 的值计算会产生 value 以用于表达式的其余部分,但它的 副作用 的更新 i 相对于分配没有顺序。)

a += a中,右操作数(a)的值计算发生在赋值之前(根据6.5.16 3),然后a +=有副作用更新 a。所以:

  • 只有一个副作用,所以没有两个未测序的副作用。
  • aa 的值计算有副作用,但它们是有序的。