Published on Sep 12,2014
461 Views
Email Post

Most of the variables have had limited and limited lifetimes, however, in some applications it becomes essential to have data which is accessible from within any block and remains in existence for the entire execution of the program. Such variables are called Global variables or External variables which can be accessed by any function using its name. Let’s look at a program that clearly shows the difference between internal and external variables.

#include<stdio.h>
Int main()
{
Int var =20;
Func();
Printf(“%d\n”,var);
System(“PAUSE”);
Return 0;
}
Void func()
{
Var+=100;
}

On compiling, the errors In func, var is undeclared and Implicit declaration of func are evident. Let’s try declaring the variable within the function main.

#include<stdio.h>
Void func();
Int main()
{
Int var=0;
Int var =20;
Func();
Printf(“%d\n”,var);

System(“PAUSE”);
Return 0;
}
Void func()
{
Var+=100;
}

On compiling, the result is ‘20’. The function func was added on top of the stack and returns this value. Here’s what happens when this program is executed.

External Variables in C

External Variables in C

External Variables in C

External Variables in C

External Variables in C

Let’s see the result after making slight changes to the code, where both the declarations are removed and then given outside.

#include<stdio.h>
Void func();
Int var = 20
Int main()
{
Func();
Printf(“%d\n”,var);

System(“PAUSE”);
Return 0;
}
Void func()
{
Var+=100;
}

The result after executing this program is ‘120’. In this case the variable var is called Global or External variable. The functions, main and func can now use var and they will be referring to the same variable. On compiling, the result will be ‘120’.

Got a question for us? Mention them in the comments section and we will get back to you.

Related Posts:

C & Data Structures

About Author
edureka
Published on Sep 12,2014

Share on

Browse Categories

Comments
2 Comments