我想知道 cout 语句中函数的执行顺序
我试过这组代码
#include < iostream >
using namespace std;
int i=0;
int sum(int a)
{
i++;
return a+i;
}
int main()
{
cout << sum(3) << sum(2) ;
return 0;
}
“我预计输出是44,但实际输出是53”
最佳答案
如此处所述:https://en.cppreference.com/w/cpp/language/eval_order
Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.
There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time
在你的行中
cout << sum(3) << sum(2)
两者的顺序operator<<
调用取决于您使用的运算符(这里是 <<
所以从左到右),但是每个子表达式的求值,即 sum(3)
和 sum(2)
没有定义的顺序,取决于编译器的心情(通常是最优化的编译方法)。
有关信息,这里是运算符关联性的列表:https://en.cppreference.com/w/cpp/language/operator_precedence
关于c++ - cout 中的函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57375317/