C++ 中的变量初始化
我的理解是一个int
变量会自动初始化为0
;然而,事实并非如此.下面的代码打印一个随机值.
My understanding is that an int
variable will be initialized to 0
automatically; however, it is not. The code below prints a random value.
int main ()
{
int a[10];
int i;
cout << i << endl;
for(int i = 0; i < 10; i++)
cout << a[i] << " ";
return 0;
}
- 哪些规则(如果有)适用于初始化?
- 具体来说,在什么情况下变量会自动初始化?
- 它是一个类/结构实例,其中默认构造函数初始化所有原始类型;比如
MyClass 实例;
- 您使用数组初始值设定项语法,例如
int a[10] = {}
(全为零)或int a[10] = {1,2};
(除前两项外全为零:a[0] == 1
和a[1] == 2
) - 同样适用于非聚合类/结构,例如我的类实例 = {};(有关这方面的更多信息,请参阅 这里)
- 这是一个全局/外部变量
- 变量是定义的
static
(无论是在函数内部还是在全局/命名空间范围内)-感谢 Jerry - it's a class/struct instance in which the default constructor initializes all primitive types; like
MyClass instance;
- you use array initializer syntax, e.g.
int a[10] = {}
(all zeroed) orint a[10] = {1,2};
(all zeroed except the first two items:a[0] == 1
anda[1] == 2
) - same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
- it's a global/extern variable
- the variable is defined
static
(no matter if inside a function or in global/namespace scope) - thanks Jerry
推荐答案
if会自动初始化
永远不要相信一个普通类型的变量(int、long、...)会自动初始化!它可能发生在像 C# 这样的语言中,但不会发生在 C &C++.
Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.
相关文章