Keyword | extern |
Storage | Data Memory |
Default Initial Value | Zero |
Scope | Global |
Life | As long as the program’s execution doesn’t come to an end. |
int i ;
int main( )
{
printf ( "\nvalue of i = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
return 0;
}
int increment( )
{
i = i + 1 ;
printf ( "\n value on incrementing i = %d", i ) ;
return 0;
}
int decrement( )
{
i = i - 1 ;
printf ( "\nvalue on decrementing i = %d", i ) ;
return 0;
}
The output of the above programs would be:
value of i = 0
value on incrementing i = 1
value on incrementing i = 2
value on decrementing i = 1
value on decrementing i = 0
The value of i is available to the functions increment( ) and decrement( ) since i has been declared outside all functions.
The
extern
modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
/*main.c*/
#include &ly;stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
/*support.c*/
#include &ly;stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Here the variable
count
is defined in main.c
and declared in support.c
as external variable. Similarly, the function write_extern()
is defined in support.c
and declared in main.c
as extern
.
Related topics:
Overview of Storage Class in C | Auto Storage Class in C | Register Storage Class in C | Static Storage Class in C | Summary of Storage Class in C
List of topics: C Programming
No comments:
Post a Comment