External variables are differ from remaining other variables. The main features of external variables as following :
Storage | Memory |
Keyword | extern |
Default initial value | Zero |
Scope | Global |
Life | As long as the program's execution doesn't come to an end. |
External variables are declared outside all functions, yet are available to all functions that care to use them.
Example of external variable or Global variable as following:
/*external variable example program*/
#include<stdio.h>
void add();
void subt();
int main()
{
printf("\ni=%d",i);
add();
add();
subt();
subt();
return 0;
}
void add()
{
int i;
i=i+1;
printf("\nAdding i = %d",i);
}
void subt()
{
int i;
i=i-1;
printf("\nSubtracting i = %d",i);
}
OUTPUT:-
Adding i= 1
Adding i = 2
Subtracting i = 1
Subtracting i = 0
/*program for global variable*/
#include<stdio.h>
int i=50;
void show();
int main()
{
int i=100;
printf("\n%d",i);
show();
return 0;
}
void show()
{
printf("\n%d",i);
}
OUTPUT:-
100
50
/*Another example of external or global variable*/
#include<stdio.h>
int i=5;
int main()
{
extern int j;
printf("\ni=%d \nj=%d",i,j);
int j=10;
return 0;
}
OUTPUT:-
i=5
j=10
Explanation: Because both variables i and j are enjoy as global variable.
You might also like to read :
In the first example,you have not declared i first in the global/any where..so the program may go wrong
ReplyDeleteyes, that's mistake. Now i written it in correct. Thanks.
Delete3rd example is not correct u initialize var inside local block and another thing is that initialization always at top inside fun.
ReplyDelete