c++全局变量初始化问题
阿神
阿神 2017-04-17 15:29:36
0
3
624
#include <iostream>

using namespace std;

bool a[5];
int main()
{
    for (int i = 0; i < 5; i++)
    {
        cout<<a[i]<<" ";
    }
    return 0;

}

以上代码中输出为0 0 0 0 0 ,但是下面代码输出却是不确定的.这是为什么?

#include <iostream>

using namespace std;

int main()
{
    bool a[5];
    for (int i = 0; i < 5; i++)
    {
        cout<<a[i]<<" ";
    }
    return 0;

}

输出176 74 183 230 255

阿神
阿神

闭关修行中......

모든 응답(3)
黄舟

两段代码中的a都是默认初始化,区别在于全局变量a在默认初始化之前会首先被0初始化(zero-initialized),而局部变量a不会(这样说并不意味着局部变量就不会被0初始化)。同时,这个默认初始化的局部变量a的值是不确定的。所以这里全局变量a的值是0,局部变量a的值不确定。

实际上一个变量是否会被0初始化与这个变量的存储期(storage duration)有关。静态变量在初始化之前会被0初始化,而自动变量不会。

8.5 Initializers
...
5 To zero-initialize an object or reference of type T means:
— if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
...
— if T is an array type, each element is zero-initialized;
6 To default-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
...
9 [ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. —end note ]
...
11 If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ]

Peter_Zhu

因为未定义的全局变量会初始化为0,但是函数内声明的局部变量没这规定

巴扎黑

一般来说,全局变量和静态变量是放在数据段中的,而局部变量是放在中的。
数据段是在编译期间就确定的,在可执行文件里面就分配好了的,所以一定会初始化。
而对于栈,我们知道是运行时分配的。当进入一个函数的时候,除了寄存器会入栈以外,还会给临时变量分配栈空间,所以局部变量对应的是一段栈地址。而栈在内存中变化很大,所以初始的值就是不确定的了。
当然,C++标准没有规定编译器具体应该将变量放到哪个区,但是一般是这么实现的。

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!