#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/