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.
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.
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.
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
精彩评论