c++ - C++ 中 std::cout 的奇怪行为

标签 c++ expression std operator-precedence expression-evaluation

#include <iostream>

int a(int &x) {
    x = -1;
    return x;
}

int main () {
    int x = 5;
    std::cout << a(x) << " " << x << std::endl;
}

为什么输出是“-1 5”?

PS:编译器是:

i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1(基于 Apple Inc. build 5658)(LLVM build 2336.11.00)

PS:未做任何优化编译

最佳答案

在这一行中:

std::cout << a(x) << " " << x << std::endl;

未指定 a(x)x 的求值顺序。发生的事情是未指定的行为,在您的情况下,编译器决定先评估 x ,然后再评估 a(x)

关于c++ - C++ 中 std::cout 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231779/

相关文章:

c++ - boost::heap::priority_queue 与 std::priority_queue 的比较器

c++ - 从字符串中提取 x、y、z 坐标?

c# - 将字节数组从 C++ 非托管 dll 传递到 C# unity

c# - 如何使用表达式构建动态查询(IN 子句)

c# - 将 Expression<Func<t, bool>> 转换为 Expression<Func<x, bool>>

c# - 如何配置 IronPython.StdLib 2.7.3

c++ - 在 C++ 代码中计算斐波那契数列

c++ - Make 不生成调试符号

java - 在新变量中使用 startDate 和 endDate 定义自己的日期间隔

c++ - Qt 可执行错误 : 0xc0000139 trying to merge c++ in qt application