are extern variables initialized to their default value?

老子叫甜甜 提交于 2019-12-10 21:05:39

问题


I know that if a char array is a global or a static local, its elements get initialized to \0's, but what if the char array is an extern variable?


回答1:


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.




回答2:


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.




回答3:


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?




回答4:


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



来源:https://stackoverflow.com/questions/13660085/are-extern-variables-initialized-to-their-default-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!