About Extern in storage Classes

Started by thiruvasagamani, Sep 22, 2008, 11:10 AM

Previous topic - Next topic

thiruvasagamani

Extern:
int a;
main()
{
extern int b;
}
f1()
{
------
------
}
int b;
f2()
{
------
------
}
f3()
{
-------
-------
}
printf("%d\n", a);
getch();
}


From the above a variable is global from the point of declaration till end of the program, 'a' is global to all the 4 functions, 'b' is global to f2(), f3() functions only, we cannot access global variable 'b' in the preceeding functions main() and f1().

Use extern to access global variable in the preceeding functions. Extern int b informs compiler that treat that as global to main() as well, thus 'b' is global to main(), f2() and f3(). New variable is not created due to extern.The global variable created else where is used in main() by extern. If extern is ommited local variable 'b' is created.

NOTE:
extern int b; This is global variable declaration, no memory is allocated, no variable is created.

eg:
1.extern int b = 35; // error
We cannot initialize the variable since no variable is created
2.extern int b;
b= 35; // correct
Global variable 'b' is modified to '35' . If global variable is declared in middle of the program, it can be accessed in the following functions.Use extern to access it in the preceeding functions.
3.
main()
{
extern int a; // error
}
f1()
{
int a;
}

From the above , extern is only for global variable but not for local.To use extern the variable must be global elsewhere.

eg:
/* file 1.c */

extern int a;
void f2()
{
----
----
}
void f3()
{
-----
-----
}


/* file 2.c */

#include " file 1.c" // this includes the file1.c
int a;
main()
{
------
------
}
void f1()
{
------
------
}
From the above 'a' is global function in file 2.c. We can use the same global variable in a different file ( file 1.c) by using extern. Thus 'a' is global to 2 files. Program is divided into 2 files, it is a single program.

eg:
int a;
main()
{
-----
-----
}
f1()
{
-----
-----
}
From the above global variable of 1 program cannot be accessed in a different program. Global variable is lost when program terminates, hence it cannot be accessed in the
other program.
Thiruvasakamani Karnan