Q37. Explain about scope of variables.
Answer:
Scope of Variables
Scope of a variable is defined as a vicinity or space within a program, where value of a given variable can be accessed. Hence, the effect of a variable can be felt only within the block where the variable has been declared.
Similarly, scope of a function can be referred to as part of a program where function can be accessed.
Scope can be classified into two types. They are,
- Local scope
- Global scope
(i) The variables which are declared within any function are called local variables.
(ii) These variables can be accessed only by the function in which they are declared.
(iii) Default value for local variable is a garbage value.
Example of Local Scope
#include<iostream.h>
#include<conio.h>
main()
{
int c; //local variable.
clrscr();
c= 7;
cout<<“Value of c is
”<<c;
getch();
return 0;
}
Output
2. Global Scope
(i) The variables which are declared outside any function are called global variables.
(ii) These variables can be accessed by all the functions in the program.
(iii) Default value for global variable is zero.
Example of Global Scope
#include<iostream.h>
#include<conio.h>
int d;
void display();
int main()
{
clrscr();
d=8;
display();
getch();
return 0;
}
void display()
{
cout<<“value of d
is:”<<d;
}
Output