c++ - cout 中的函数调用顺序

标签 c++ c++14 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;
}

“我预计输出是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/

相关文章:

c++ - 使用 shared_ptr : C++ 管理多个对象

class - 模板参数 : enum, 类或枚举类

c++ - 无法将 vector <string> 输出到文件

c++ - 我能得到一个指向 nullptr 的指针吗,它有效吗

运行时的 C++ 编译

c++ - 使用更新的 C++ 标准向后移植的类型和模板扩展命名空间 std

c++ - 由于某种原因,在输入 cin 文本后,cout 显示为空白。有任何想法吗?

c++ - 错误 : 'cout' : undeclared identifier; though I've included iostream header file in program

C++03 vector 作为缓冲类

ide - C++ 14支持编辑器/IDE