为什么新变量的初始化本身有效?
考虑一些代码:
#include <iostream>
int main()
{
using std::cout;
int a=3;
cout << "a="<<a<<"\n";
{
int a=a;
cout << "new a = " << a << "\n";
a=5;
cout << "a = " << a << "\n";
}
cout << "old a = " << a << "\n";
}
我希望它可以打印,
a=3
new a = 3
changed a = 5
old a = 3
但是我得到的实际上似乎在第二行中说new A = 0
。我认为它可以像类构造函数中的初始化列表一样工作,在该类别的构造函数中可以写作,
C::C(int a) : a(a) {}
但由于某种原因,这是不同的。首先,完全删除外部代码不会导致汇编错误。因此,我假设int a = a;
是有效的。打开所有编译器警告会导致这一点:
test.cpp: In function ‘int main()’:
test.cpp:10:15: warning: ‘a’ is used uninitialized in this function
int a=a;
所以我现在的问题:为什么这种语法完全有效?编译器为什么不说“未定义变量A”之类的话?
Consider some code:
#include <iostream>
int main()
{
using std::cout;
int a=3;
cout << "a="<<a<<"\n";
{
int a=a;
cout << "new a = " << a << "\n";
a=5;
cout << "a = " << a << "\n";
}
cout << "old a = " << a << "\n";
}
I'd expect it to print
a=3
new a = 3
changed a = 5
old a = 3
But what I get actually appears to say new a = 0
in the second line. I thought that it would work like initialization list in a class' constructor, where one can write like
C::C(int a) : a(a) {}
But for some reason this is different. First, removing the outer code completely doesn't result in a compilation error. So I assume that int a=a;
is valid. Turning on all the compiler warnings leads to this:
test.cpp: In function ‘int main()’:
test.cpp:10:15: warning: ‘a’ is used uninitialized in this function
int a=a;
So my question now: why is this syntax valid at all? Why doesn't the compiler say something like "undefined variable a"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它在句法上有效,因为变量的声明点是在其初始评估之前的,并且该名称在此之后可用。这允许较少的狡猾初始化,例如
合法使用要初始化的变量的名称(而不是值)。
这在行为上是无效的,因为使用非初始化对象的值会产生不确定的行为。这不是需要诊断的错误(因为通常,很难或不可能分析程序流以查看是否已初始化对象),但是正如您指出的那样,许多编译器会对此类直接案例发出警告。
It's syntactically valid, since the variable's point of declaration comes before its initialiser, and the name is available anywhere after that point. This allows less dodgy initialisations like
which legitimately uses the name (but not the value) of the variable being initialised.
It's behaviourally invalid, since using the value of an uninitialised object gives undefined behaviour. That's not an error that requires diagnosis (since, in general, it can be difficult or impossible to analyse the program flow to see whether an object has been initialised), but as you note, many compilers will give a warning for straightforward cases like this.