程序一:
#include <iostream>
using namespace std;
int a = 5;
int fun1() {
a = 17;
return 3;
}
int main() {
// Even though C languages are left associative,
// this line of code evaluates fun1() first:
a = a + fun1();
// a = 17+3
printf("%d",a);
a = fun1()+a;
printf("\n%d",a);
return 0;
}
输出:
20
20
方案二:
int a = 10;
int fun(){
a= 15;
return 30;
}
int main(void) {
// whereas in this example, fun() is evaluated last:
int x = a + 10 + fun();
// x = 10 + 10 + 30
a= 10;
int y = fun() + 10 + a;
printf(" x = %d \n y = %d \n",x,y);
return 0;
}
输出:
x = 50
y = 55
为什么程序 1 首先对 fun1() 求值,而在程序 2 中,当 fun() 放在表达式的末尾时最后求值?
据我所知,基于 C 的语言是左关联的,那么为什么程序 1 表现得很奇怪?
最佳答案
从历史上看,函数调用的参数评估顺序是未指定的。这意味着对于调用
foo(bar(), baz());
如果需要调用 bar()
而不是 baz()
,则由编译器决定,反之亦然。请记住,调用运算符是通用函数调用的另一种情况,即 baz() + bar()
在语义上与 operator+(baz(), bar())
.
出于实际目的,考虑到这是许多函数调用 ABI 将参数推送到堆栈的顺序,编译器过去常常从最后到第评估参数。
关于c++ - C++ 表达式中的运算符优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49759641/