Scope of variables

Scope is a region in a programming language .Variable scope is the region in the program where you can define and use the variables and it can be used only in that scope.

There are 2 types of variables:
1. Local variables
2. Global variables

Local variables – The scope of local variables is within the function only, the variables which are defined inside the function can’t be accessed outside the function.

Global variables – Scope of the the global variables is throughout the program.These variables can be accessed anywhere in the program.
Mostly global variables are declared after the header file and before the main() function.

In the below example, variables “a,b,c,d” can be accessed anywhere in the program including body of “fun()” function as they are global variables.
Now if we look at the variables inside the function fun(), they are local variables and can only be accessed from within the function fun(), if we try to use local variables inside the main function it will give an error.

Example of Global and Local variables