为什么在这个C ++代码中i == 0的值? [英] Why is the value of i == 0 in this C++ code?
本文介绍了为什么在这个C ++代码中i == 0的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对以下代码感到困惑:
I am confused about the following code:
#include <iostream>
int i = 1;
int main()
{
int i = i;
std::cout << "i: " << i << "\n";
return 0;
}
输出:
i: 0
预期运行上面的代码会打印 1
。
推荐答案
您正在初始化 i
与自身。 i
int i = i;
中的 i
都是内层而不是外层。这是未定义的行为,您可能会遇到 0
或任何。
You are initializing i
with itself. The both i
's in int i = i;
are the inner one not the outer one. This is undefined behavior and you may get 0
or anything may happen.
如果您要将外部 i
分配给内部 i
,这是正确的方法。
This is the right way if you want to assign the outer i
to the inner i
.
#include <iostream>
int i = 1;
int main()
{
int i = ::i;
std::cout << "i: " << i << "\n";
return 0;
}
BTW,您应仔细阅读所有编译器警告。如果您自己可以看到问题:
BTW, You should carefully read all the compiler warnings. If you did you could see the problem yourself:
警告'i'在此函数中未初始化
warning 'i' is used uninitialized in this function
这篇关于为什么在这个C ++代码中i == 0的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文