gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:44 30 4
gpt4 key购买 nike

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

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com