View Feed
group-icon
Coffee Room
Discuss anything here - everything that you wish to discuss with fellow engineers.
12940 Members
Join this group to post and comment.

What is the use of extern keyword in c ?

hiiii CEan


there is compilation error in first program here even out is a global variable but it is not for main

and in second program out is also declare globally but out put is 100 because of extern so can any one explain me how extern work in this program.

main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.

and

main()

{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
Ankita Katdare
Ankita Katdare • Sep 9, 2012
hare singh nayak

In your first program you get a compiler error: undefined symbol out in function main, because according to the syntax a variable is available for use only from the point of declaration. Even though 'out' is a global variable, it is not available for main. Hence an error.

Whereas in the second program, you get the correct output because the 'extern' keyword extends the visibility of the C variables or functions.

To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable.
When a variable is defined, the compiler allocates memory for that variable and possibly also initializes its contents to some value.
When a variable is declared, the compiler requires that the variable be defined elsewhere.

In this case, 'extern' makes sure that the variable 'out' is available in 'main' function.
optimystix@
optimystix@ • Sep 9, 2012
extern
Allows one module of your program to access a global variable or function declared in another module of your program.😀
sulochana anand
sulochana anand • Sep 9, 2012
extern variables are global variables.it can b used across different files.

Share this content on your social channels -