简体   繁体   中英

are extern variables initialized to their default value?

我知道如果一个char数组是一个全局或一个静态局部,它的元素初始化为\\ 0,但是如果char数组是一个外部变量怎么办?

If the variable was declared as extern but is nonglobal, it too receives the same initialization handling. For instance

namespace A { extern int x; int x;}

This nonglobal variable will be initialized to zero. All namespace scope variables receive this handling.

extern is only a declaration .
Whether the variable will be initialized depends on the definition .

Also, the value of the variable will depend on type of initialization. The C++ standard defines 3 types of initialization:

  • Zero-initialize
  • Default-Initialize
  • Value-Initialize

C++03 Standard 8.5/5 aptly defines each.

Good Read:

What is the difference between a definition and a declaration?

An extern variable is just a declaration. The variable is initialized in the module that defined it. Since in that module the variable is a global, it gets zero-initialized.

The extern keyword only declares that the variable exists, it does not define its value. because of global scope it initialised to 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM