【发布时间】:2015-03-24 23:52:08
【问题描述】:
考虑一些代码:
#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”之类的东西?
【问题讨论】:
-
@101010 Ahem?
-
@ShafikYaghmour 如果您将其作为答案和一个简短的要点发布,您将获得一些选票,并且此问题可以标记为已回答。
-
@BjörnPollex 它是重复的,非常接近我发布的第二个链接,但在某个地方可能有更接近的重复,但它应该作为重复关闭。
标签: c++ initialization undefined-behavior variable-declaration