In this C++ Tutorial you will learn about Scope of Variables in Function, Local Variables – Scope of Local Variables, Global Variables – Scope of Global Variables.
The scope of the variables can be broadly be classified as
- Local Variables
- Global Variables
Local Variables:
The variables defined local to the block of the function would be accessible only within the block of the function and not outside the function. Such variables are called local variables. That is in other words the scope of the local variables is limited to the function in which these variables are declared.
Let us see this with a small example:
#include <iostream>
using namespace std;
int exforsys(int,int);
void main( )
{
int b;
int s=5,u=6;
b=exforsys(s,u);
cout << "n The Output is:" << b;
}
int exforsys(int x,int y)
{
int z;
z=x+y;
return(z);
}
The output of the above example is:
In the above program the variables x, y, z are accessible only inside the function exforsys( ) and their scope is limited only to the function exforsys( ) and not outside the function. Thus the variables x, y, z are local to the function exforsys. Similarly one would not be able to access variable b inside the function exforsys as such. This is because variable b is local to function main.
Global Variables:
Global variables are one which are visible in any part of the program code and can be used within all functions and outside all functions used in the program. The method of declaring global variables is to declare the variable outside the function or block.
For instance
#include <iostream.h>
int x,y,z; //Global Variables
float a,b,c; //Global Variables
void main( )
{
int s,u; //Local Variables
float w,q; //Local Variables
...
...
}
In the above the integer variables x, y and z and the float variables a, b and c which are declared outside the block are global variables and the integer variables s and u and the float variables w and q which are declared inside the function block are called local variables.
Thus the scope of global variables is between the point of declaration and the end of compilation unit whereas scope of local variables is between the point of declaration and the end of innermost enclosing compound statement.
Let us see an example which has number of local and global variable declarations with number of inner blocks to understand the concept of local and global variables scope in detail.
...
int g;
void main( )
{
...
int a;
{
int b;
b=25;
a=45;
g=65; // end of scope for variable b
}
a=50;
exforsys( );
...
}// end of scope for variable a
void exforsys( )
{
g = 30; //Scope of g is throughout the program and so is used between function calls
}
In the context of scope of variables in functions comes the important concept named as storage class which is discussed in detail in next section.