2011-06-29 78 views
1

我的理解是靜態變量放在二進制(BSS段)的未初始化的變量部分得到等等這些都是安全的假設爲被初始化爲0變量在未命名的命名空間中自動初始化爲0?

但是我有一個無名命名空間中定義的函數。在函數內部,有一個char數組被聲明爲未明確初始化爲0.這會被自動初始化爲0嗎?怎麼樣的變量沒有聲明爲靜態的,而是在未命名的命名空間中定義的?那麼靜態函數的局部變量呢?

回答

1

千萬不要依賴於爲你初始化/完成的事情。隨着事情可能發生變化,只需進行初始化即可,並且您將不知情地被捕獲。

1

你不能依賴一個變量被自動初始化爲任何值。即使在某些情況下會不斷髮生這種情況,只要更改編譯器就可以產生完全不同的結果。最安全的是始終初始化每個變量以確保其價值。您還應該初始化static variables。變量屬於命名空間這一事實並不重要。

2

函數局部變量不會自動初始化爲零,無論函數是匿名命名空間,靜態還是其他。這是因爲函數內部的局部變量不是靜態變量。要使局部變量具有靜態存儲持續時間,您必須用static明確標記它。

int foo; // static storage duration (because it's global) automatically zero-initialized 

static int foo2; // static storage duration (because it's global) automatically zero-initialized. The static keyword just gives the name 'foo2' internal linkage and has nothing to do with static storage duration. 

namespace { 

    int foo; // static storage duration, automatically zero-initialized 

    void bar() { 
     int f; // local variable, not automatically zero-initialized 

     static int g; // static storage duration (because of the keyword static), automatically zero-initialized 
    } 
} 
相關問題