gpt4 book ai didi

c++ - 为什么当条件为真时 x 的值没有改变?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:40 25 4
gpt4 key购买 nike

int x = 1;
if (x > 0)
int x = 2;
cout << x;

我预计输出为 2 因为条件为真,但这里发生了什么?

我收到了 1 作为输出。

最佳答案

你已经 shadowed变量。当在一个范围内声明的变量与在外部范围内声明的变量同名时,就会发生这种情况。

进行此修改将提供您期望的输出:

int x = 1;
if (x > 0) {
x = 2; // now you're modifying the same x
}
cout << x;

关于c++ - 为什么当条件为真时 x 的值没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51545532/

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