Page 93 - Modular_V2.0_C++_Flikpbook
P. 93
SCOPE OF VARIABLES
The scope of a variable means how the different parts of the program can access that variable.
There are two main types of scopes for variables in C++: local and global.
Local Variables
The variables which are declared in the body of a function or block are called local variables for
that function. You can use these variables only inside the function in which they are declared. If
you try to use the local variables outside their scope, C++ compiler will show an error message.
Global Variables
The variables that are declared outside of all the functions are called global variables. Global
variables can be used by any function in the program. Generally, global variables are declared
just below the preprocessor directive.
For example:
#include<iostream.h>
#include<conio.h>
void fun1();
void fun2();
char grade;
void main()
{
clrscr();
fun1();
fun2();
getch();
DOSBox 0.74, Cpu speed: max 100% cycles,
}
Your grade is: B
void fun1()
Your grade is: A_
{
grade = 'B';
cout<< "Your grade is: " << grade << "\n";
}
void fun2()
{
grade = 'A';
cout<< "Your grade is: " << grade;
}
When you run the above program, you will get two different outputs from both the functions,
which means both the functions are able to access the global variable grade.
91
Functions in C++

