C++的變量初始化

Storage classes

The storage for variables with?global?or?namespace scopeis allocated for the entire duration of the program. This is known asstatic storage, and it contrasts with the storage forlocal variables(those declared within a block). These use what is known as automatic storage. The storage for local variables is only available during the block in which they are declared; after that, that same storage may be used for a local variable of some other function, or used otherwise.

But there is another substantial difference between variables withstatic storageand variables withautomatic storage:

- Variables with?static storage(such as global variables) that are not explicitly initialized are automatically initialized to zeroes.

- Variables with?automatic storage(such as local variables) that are not explicitly initialized are left uninitialized, and thus have an undetermined value.

Array

number of elements in the array, must be a?constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

By default, regular arrays of?local scope(for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.

Static arrays, and those declared directly in a namespace (outside any function), are always initialized. If no explicit initializer is specified, all the elements are default-initialized (with zeroes, for fundamental types).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容