Monday, April 16, 2012

Extern storage class in C!!!

External storage class is used to give the reference for the global variable which is visible to the whole application/program. When you declare variable as extern, variable can't be initialised, its only a declaration. Memory will not be allocated to the extern variable. But it will point to the variable which is already declared somewhere in other file. Extern is the default for all global variables and functions.
  • Keyword: extern
  • Default value: zero if not initialised .
  • Memory Location: Main memory
  • Scope: Global to the whole program/application
  • Lifetime: Global to the whole program/application

Sample code for Extern storage class:

// file name is file1.c and code is below

static int i=10; // i is static, so its scope is limited to this file only

// file name is file2.c  and code is below

extern int i; // i is extern, so i value is somewhere in ohter file 
extern void print();
void print()
    printf("i is %d\n",i); // will get error here, because in file1.c i is static

Output :
i is 10

When you have multiple files, and you declared a global variable in on file and you want to use the same varaibel in other file, you need to declare the variable as extern in other file. Just for understanding and letting to know the developer, we are using extern. By default global variables are extern, if you not declare as extern, compiler by default assumes all global variable are extern variables.

No comments:

Popular Posts