Difference between extern int a; extern int a=42;

匿名 (未验证) 提交于 2019-12-03 00:50:01

问题:

While I was reading the answers of Use of 'extern' keyword while defining the variable

One of the user answered these way

 extern int a;       //  not a definition   extern int a = 42;  //  definition  

I was expecting both are not definitions but declarations. I was thinking Both statements says that the variable is defined outside the function and we have to use extern keyword to use it. is this a mistake by him or is it really a definition ? I know that

extern int a; // variable is already defined but its outside the function extern int a=42 ; //I guess a variable is assigned a value but not a definition  

but these statement

extern int a = 42; // user said its a definition and now i got  confused 

Please clear me with these.

回答1:

Whenever initialisation is attempted, the statement becomes a definition, no matter that extern is used. The extern keyword is redundant in such a case because, by default, symbols not marked static already have external linkage.

It doesn't make sense to declare an external variable and set its initial value in the current compilation unit, that's a contradiction.



回答2:

extern int a; is a declaration. It does not allocate space for storing a.

extern int a = 42; is a definition. It allocates space to store the int value a and assigns it the value 42.



回答3:

here the variables are declared inside the main() function where its definition was defined outside in the global declaration section

extern int a; //This is a declaration  extern int a=42; //This is a definition 


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