External Storage Class
External Storage Class:
· Values stores in memory only.
· Default value of external storage value is zero.
· Variable scope is global.
· Life of variable is as long as the program’s execution doesn’t come to end
· External variables declared outside function, So that function may use it. These variables are available to all functions.
#include<stdio.h> void useFile(); /* this variable is external variable, its default value will be zero */ char* fileName="test.txt"; main( ) { printf("File main function - %s\n",fileName); useFile(); } void useFile() { printf("File useFile function - %s\n\n",fileName); } |
In this program, we define an external variable (fileName) which is a char pointer. This variable is available in all function. We use filename in both function and we can see output in attached image.
Example 2:
#include<stdio.h> int x = 1 ; main( ) { extern int y ; // declaration printf ( "\n%d %d", x, y ) ; } int y = 2 ; |
Here x and y both are external variables as both are defined outside of functions.
- In main function we defined extern int y. this is declaration of y variable and int y=2 is definition. As we declare a variable it will not reserve memory.
- In this function we required declaration of y variable because its definition is after the main function and we are using this variable in main function. If we did not declare it before we use , it will show compile error.
- To declare a variable we use extern keyword.
- Local variable have more preference then global variable.
Comments
Post a Comment