#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
黄舟2017-04-17 15:31:36
兩段程式碼中的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 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 Toaldefault-initi 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 access default );
— if T is an array type, each element is default-initialized;
— otherwise, no initialization is performed.
...
9 [ 註: Every object of static 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 s 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, static or thread storage duration are zero-initialized, s. 🎜>回覆0
巴扎黑2017-04-17 15:31:36
一般來說,全域變數和靜態變數是放在資料段中的,而局部變數是放在堆疊中的。
資料段是在編譯期間就決定的,在執行檔裡面就分配好了的,所以一定會初始化。
而對於堆疊,我們知道是運行時分配的。當進入函數的時候,除了暫存器會入堆疊以外,還會給臨時變數分配堆疊空間,所以局部變數對應的是一段堆疊位址。而棧在記憶體中變化很大,所以初始的值就是不確定的了。
當然,C++標準沒有規定編譯器具體應該將變數放到哪個區,但是一般是這樣實現的。