By scope of a variable we mean which part of the code a variable is accessible (visible) to .A variable can have many scopes in c++. let’s discuss some of them .
According to Scope, variables is divided into two categories:-
Local Variables
Global Variables
Local Variable
Local variables are those variables that are defined in a small block of the program such as function, control statement block etc. Such variables are used only by the same block.
- A variable inside the function/block is a local variable .
- Local Variables is inside the function.
- The default value of the Local variables is ‘garbage value’.
Example :
#include "stdio.h";
int main()
{
int a,b,c; // local variables
a =10;
b = 30;
c = a + b;
printf("%d",c);
}
Here a, b, c all are local variables and can not be used by any other function except main. On execution of the program the compiler prints 40
Global variable
As oppose to local variable a global variable is out side every function and is accessible to all the functions and the value of a global variable can be changed by any function.
Global variables are those variable whose scope is in whole program. These variables are defined at the beginning of the program.
- Global variables are out of the function.
- Global variables have visibility throughout the program.
- The default value of ‘Global Variables’ is ‘0’.
Example :
Global Variable
#include "stdio.h";
int d=20; // global variable
int main()
{
int a,b,c; // local variables
a = 10;
b = 30;
d = d + 10;
c = a + b + d;
printf("%d",c);
return c;
}
output