c++ - 奇怪的 cout 输出(代码块 codeblocks-16.01mingw-setup.exe)

标签 c++

当我运行这个程序时,我得到奇怪的输出 1132。有人能解释一下为什么是 1132 吗?

//main.cpp
#include <iostream>
using namespace std;

int f1(int &a){return a++;}
int f2(int &a){return ++a;}

int main(){
    int x, y;
    int *px, *py;
    x = 1;
    y = 2;
    px = &x;
    py = &y;
    cout << f1(*px) << *px << f2(*py) << *py << "\n";

    return 0;
}

最佳答案

在您的案例中,评估顺序是从右到左。

请注意,不能保证从左到右求值。

所以顺序是:

  1. *py

  2. f2(*py)

  3. *px

  4. f1(*px)

然后才有<<运算符运行(并按预期从左到右进行评估)

关于c++ - 奇怪的 cout 输出(代码块 codeblocks-16.01mingw-setup.exe),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390646/

相关文章:

c++ - 构造函数的删除是否继承?

c++ - 为什么内存地址是偶数?

c++ - 在 MFC 应用程序中未调用重叠的 WSARecv() 回调

c++ - 放置新的和析构函数

c++ - 构建 Qt 程序时遇到问题

C# vs C++ 三元运算符

c++ - 使用 insert c++ 增加 map 中的值

C++:在函数指针 vector 中存储和调用函数指针

c++ - 在 OpenCV 中创建随机彩色图像

c++ - 使用排序函数根据函数对列表进行排序