1. Home >
  2. Apps >
  3. Groups >

What is the use of extern keyword in c ?

Question asked by hare singh nayak in #Coffee Room on Sep 9, 2012
hare singh nayak
hare singh nayak · Sep 9, 2012
Rank D2 - MASTER
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
Posted in: #Coffee Room
Ankita Katdare
Ankita Katdare · Sep 9, 2012
Rank A1 - PRO
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
Rank D1 - MASTER
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
Rank D1 - MASTER
extern variables are global variables.it can b used across different files.

You must log-in or sign-up to reply to this post.

Click to Log-In or Sign-Up