cout 中的函数调用顺序

order of function call inside cout

我想知道 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;
}

"I expected the output to be 44, but the actual output is 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