<分区>
考虑一些代码:
#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;
那么我现在的问题是:为什么这个语法完全有效?为什么编译器不说“ undefined variable a”之类的东西?