Variable declaration
Title
Question
What is the difference between a global declaration and Extern. How it differs as both does the same operation
C-and-Cpp Scope-Of-Variables 08-09 min 0-10 sec
Answers:
Global declaration also allocates a memory location for the variable, whereas extern simply tells that there is a variable by that name which someone else has allocated in some other file.
The 'extern' keyword is used to make local variables to global. Let us take an example:
/*Program1*/
#include<stdio.h>
void main()
{
int a; //local variable
void disp();
a=10;
printf("a=%d",a);
disp();
printf("\na=%d",a);
}
int a;
void disp()
{
a=20;
printf("\na=%d",a);
}
OUTPUT:
a=10
a=20
a=10
Here the variable a in main will be treated as local automatic variable but if we want to use it as global variable 'a' then extern keyword will be used before the declaration like:
extern int a;
=>
/*Program2*/
#include<stdio.h>
void main()
{
extern int a; //global variable
void disp();
a=10;
printf("a=%d",a);
disp();
printf("\na=%d",a);
}
int a;
void disp()
{
a=20;
printf("\na=%d",a);
}
OUTPUT:
a=10
a=20
a=20
Thank you.....
Dr. Anand Kr. Pandey,
T. N. B. College, Bhagalpur
(9534329101)
Login to add comment