c++全局变量初始化问题

查看:95
本文介绍了c++全局变量初始化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

#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

解决方案

两段代码中的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 ]

这篇关于c++全局变量初始化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆