in Programming in C
385 views
3 votes
3 votes

What is the difference between EXTERN keyword with function & EXTERN keword with variables ?

in Programming in C
by
385 views

1 Answer

2 votes
2 votes
Best answer

Functions themselves are always external, because C does not allow functions to be defined inside other functions.

This is taken from C programming by Dennis Ritchie. 

There is no meaning of writing extern infront of a function, since functions are always external in C. It will compile.

Variables can be external as well as internal. Internal variables are those defined inside a function or a block. Automatic variables and register variables are always internal. Variables defined outside of any function are global variables, or external variables. They can be accessed by any function defined after the variable definition.

So, where's the use of extern keyword??

It is used to access gloabal variables defined in some other file of the same program.

FILE 1:

   extern int a;

   void func(int k);           // a function which uses the global variable a

FILE 2:

   int a = 10;                   //variable 'a' defined in FILE 2

In this case, the variable a is defined in FILE2, and used in FILE1 by func(), and before using 'a' it is declared in FILE1 using

extern int a;

For better understanding, I recommend you to go through The C Programming Language by Dennis Ritchie, page 73, section 4.3 External Variables.

selected by

2 Comments

in file1 if we didnt write “extern” keyword even though then this program works so why we use “extern” ?
0
0
If we do not write extern in file 1 that means that there are 2 definitions of variable a. By definition I mean that there are 2 saperate blocks allocated to variable a(in file 1) and variable a(in file 2), meaning these to are completely saperate variables. Whereas when we are writing extern in file 1 we are referencing the same variable which has only one block of memory allocated and is defined in file 2. There can be many extern declaration of a variables but only one definition. Hope this clears your confusion
0
0

Related questions