5

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.

Community
  • 1
  • 1
niko
  • 9,285
  • 27
  • 84
  • 131
  • The declarations being discussed in the linked questions are all assumed to be file scoped declarations, not function scoped. – CB Bailey Sep 30 '11 at 12:30

3 Answers3

7

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.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • wow ! i did not know that c is really a language with a miracles binded in it – niko Sep 30 '11 at 12:30
  • so You mean extern int a = 42 ; is nothing but int a = 42 ? right – niko Sep 30 '11 at 12:31
  • okay I have got some thoughts on my mind after seeing you answer let me try it on my compiler and update my question if i have any issues with that. but thanks ! – niko Sep 30 '11 at 12:31
5

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.

qbert220
  • 11,220
  • 4
  • 31
  • 31
0

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
Shubham Mittal
  • 1,545
  • 18
  • 21
Gouse Shaik
  • 340
  • 1
  • 2
  • 15