2,623 views
3 votes
3 votes

extern int var;

int main(void)

{

 var = 10;   // why it is not considered as definition in prog 

 return 0;

}

Why this is creating error saying (var is not defined).But as per rule 

-"by externing a variable we can use the variables anywhere in the program provided we know the declaration of them and the variable is defined somewhere."?

1 Answer

6 votes
6 votes

External variable

As the name suggest , they are external to any function which means they are defined always outside of any function. Actually when you declare the external variable (declaration can be inside of any function or outside) you make a promise with your compiler that you have defined that variable somewhere outside of any function. 

first it's good to know what does it mean by Declaration and Definition.

Extern int a;  is actually a declaration. Declaration is just a hint to compiler that this kind of variable/function may be use somewhere so better you know about it now. Memory is not allocated during declaration.

Extern int a=5;  is actually definition but as its external variable, you can't use it inside any function. where ever outside you define extern variable , its responsibility of linker to find it and use it. Variables declared inside some function or block (i mean to say local variable)have No Linkage. You make then extern and put the definition outside blocks and linker will find then for those who need that extern variable at linking time.

In you program the linker won't be able to find definition of your declared extern variable (as you didn't define it outside and linker only search outside , in that way only linker works) so it's okay no problem , no error would be there (either it's bad programming) so ultimately there is no memory allocated for your variable. but the tragedy is you defined extern variable inside some function so here compiler would catch it at compiling time and will think , there is even no memory is allocated for that variable and some superman is trying to update its value. Compiler would say to itself ohh someone is making fun of me as he is saying me to update a variable which even don't exists :)

hope you get it tell me if more i can tell you.

Related questions

2 votes
2 votes
1 answer
1
rahul sharma 5 asked Nov 23, 2017
1,055 views
#include <stdio.h int main() { int a=10; extern int a; return 0;} Why this gives compilation error? Extern is just a declaration.So why it is giving error on c...
0 votes
0 votes
1 answer
2
Na462 asked Nov 19, 2018
1,502 views
1 votes
1 votes
0 answers
3
2 votes
2 votes
2 answers
4
targate2018 asked Jan 15, 2018
1,445 views
extern int i; int i = 10; i = 5; int main() { printf("%d", i); return 0; }The output for the above code is _______