【发布时间】:2021-08-10 21:05:35
【问题描述】:
int p(int *ptrP){
*ptrP=20;
return *ptrP;
}
int q(int *ptrQ){
*ptrQ=30;
return *ptrQ;
}
int main(){
int answer=0,a=10;
answer=p(&a)+q(&a); // line Alpha,for discussions sake
printf(" answer=%d a=%d ",answer,a );
}
输出:answer=50 a=30;
在 line Alpha answer=q(&a)+p(&a) 中交换函数调用导致 answer=50 a=20,这可以通过说函数调用优先级从左到右来证明,但是当我们将 line alpha 更改为 answer=p(&a)+a+q(&a); 时,输出是answer=70 a=30。
函数调用在优先级表中的位置是什么? foo()+10 和 10+foo 是等效的语句吗?
【问题讨论】:
-
在您修改后的带有 3 个操作数的行中,答案与从左到右进行评估是一致的。
-
还有,C++ 的哪个版本。 C++20改变了这方面的规则
-
与直觉相反,这与运算符优先级无关。如果我们查看
(3+5) * (6+7),没有关于是先计算(3+5)还是(6+7)的数学规则。这是一个关于“执行顺序”的问题。 -
我刚刚在阅读 Herbert Schildt 的 C++ The Complete Reference,(第四版)它说 Ref(pg 52)
Order of Evaluation :: Neither C nor C++ specifies the order in which the subexpressions of an expression are evaluated. This leaves the compiler free to rearrange an expression to produce more optimal code. However, it also means that your code should never rely upon the order in which subexpressions are evaluated. For example, the expression x = f1() + f2(); does not ensure that f1( ) will be called before f2( ).这个规则是否适用于当前版本的 C 和 C++跨度>
标签: c++ function operator-precedence function-call order-of-execution