c - C语言的求值顺序

标签 c language-lawyer operator-precedence sequence-points order-of-execution

  1. x+=x*=x 是未定义的行为吗?
  2. 谁能在Order of evaluation中解释这条规则? ?什么是“单一评价”? “单一评估”的反义词是什么?

    14) With respect to an indeterminately-sequenced function call, the operation of compound assignment operators, and both prefix and postfix forms of increment and decrement operators are single evaluations.

最佳答案

x+=x*=x 具有未定义的行为,因为 x 在序列点之间被分配了两次。


C11中14)对应的文字,C17说

A compound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation.

我认为它的意思是

int x = 0;

int foo(void) {
    x = 5;
    return x;
}

int main(void) {
    int y = foo() + (x += 2); 
}

将有或者

的行为
int main(void) {
    int _tmp = x += 2;
    int y = foo() + _tmp; 
}

int main(void) {
    int _tmp = foo();
    int y = _tmp + (x += 2); 
}

不能分割成例如

int main(void) {
    int _tmp = x;
    int _tmp2 = foo();
    x = _tmp + 2;
    int y = _tmp2 + x; 
}

注意这个保证在C11中是新增的,在C89、C99中是不存在的。

关于c - C语言的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957637/

相关文章:

用于填充结构字段的 C 预处理器宏

c - 为什么我会得到 Seg-Fa

c++ - 为什么在 C++ 中进行移位操作后,位域的无符号整数会变成有符号整数?

c++ - `static constexpr auto` 使用未命名枚举初始化的数据成员

javascript - 当表达式不可能为 TRUE 时,它的计算结果为 TRUE,不是吗?

c - 位域和存储单元

c - 使用 c 进行 GUI 编程简介

c - 在动态 bool 数组上使用 memset 是否定义明确?

c - 为什么按位 'and' 、 'xor' 和 'or' 具有不同的优先级?

c - 中缀到后缀表达式