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).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容