Variables Scope in C++
Variables are defined in three different ways.
- Inside the functions or blocks
- As a function parameters
- Outside the functions
As a function parameters i will discuss this in Functions lecture.
Local Variables:
Variables which are defined inside the functions or blocks are called as Local variables.These variables can be used by the statements defined inside the same functions.
They are not accessible to statements or functions which are not the part of same functions.
Local variables are not initialized by the system , you have to initialize them.
They are not accessible to statements or functions which are not the part of same functions.
Local variables are not initialized by the system , you have to initialize them.
Look at this Example, i am going to define local variables which are accessible to statements defined in the main( ) function
Program code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int x , y;
cout<< "numbers from 1 t0 50 "<<endl<<endl;
for(int i=0; i<50 ; i++)
{
x = i +1 ;
cout<< x << " " ;
}
getch();
}
Output:
After compiling and execution of above program code , i obtained the following result
Global Variables:
The variables which are defined outside the functions and can be accessed any where in the program are called as global variables.
Global variables are usually defined on the top of the program. They retain their value throughout the life time of program.
Global variables are automatically initialized by the system.
Global variables are automatically initialized by the system.
Look at this example, i am going to define global variable and local variables in the same program. Variable z acting as a global variable and variables x,y acting as local variables.
Program code:
#include<iostream>
#include<conio.h>
using namespace std;
int z = 10 ;
int main()
{
int x , y;
cout<< "numbers from 1 t0 5 "<<endl<<endl;
for(int i=0; i<5 ; i++)
{
x = i +1 ;
cout<< x << " " ;
}
cout<<endl<<endl;
cout <<"Accessing Global variable z in the main function" <<endl<< z;
getch();
}
Output:
After compiling and execution of above program, result of above program is ...
Click to enlarge it.
Keep practicing on it.
No comments:
Post a Comment