extern keyword in c

Sunday, December 18, 2016 Unknown 0 Comments

extern is a keyword which extends the visibility of a variable. A variable with this keyword can be used in different files
syntax
extern var_data_type var_name;
eg.
extern int x;
Now will focus on some cases
case 1:
extern int i;
int main(){
i=8;
return 0;
}
will not be compiled successfully, because extern variable i is not defined hence there is no memory allocation for this variable and main function tries to change it's value, hence compilation fails here.
case 2:
#include<someotherfile.h>
extern int i;
int main(){
i=8;
return 0;
}
will compile successfully. Though variable i is not defined here, but compiler assumes it's definition in included header file.
case 3:
extern int i=0;
int main(){
i=8;
return 0;
}
will compile successfully, because variable i is defined at the time of declaration hence memory is allocated and main() function can change it's value.

0 comments: