Scope refers to the visibility of variables. In other words, a scope is a section of a program, and the scope of variables refers to the section of the program where the variables are visible. Variable is declared and used within that region. Also, variables declared within the block cannot be accessed outside that block.
Depending on the region, there are three types of scope that are declared and used:
- Local variables: inside a function or a block.
- Global variables: outside of all functions.
- Formal parameters: function parameters.
1. Local Variable:
A variable that is declared within the body of the function or block is called a local variable. This variable is used only within that block or function where it was created, other classes cannot access it. And is destroyed after exiting the block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> void differentFunc() { /*local variable of this function */ int a = 10; printf("%d : Variable from differentFunc function\n", a); } int main() { /*local variable of function main*/ int a = 50; { /*local variable for this block*/ int a = 30; printf("%d : Variable inside the block\n", a); } printf("%d : Variable of main\n", a); //calling function differentFunc(); } |
The output of Local variable in C:
1 2 3 | 30 : Variable inside the block 50 : Variable of main 10 : Variable of main |
2. Global Variable:
Global variables are declared outside any functions and usually at the top of the program as shown below.
They can be used in the program inside any block of code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> //Global Variable int a = 20; void funGlobal() { /*local variable with same name on different block*/ int a = 50; printf("%d : Inside funGlobal Function\n", a); } int main() { printf("%d : Inside main\n", a); //caling the function funGlobal(); } |
The Output of Global Variable in C.
1 2 | 20 : Inside main 50 : Inside funGlobal Function |
3. Formal Parameters
Formal Parameters are the parameters that are used inside the body of a function. Formal parameters are treated as local variables in that function and get a priority over the global variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <stdio.h> /*Global variable*/ int a = 20; void funFormal(int a) { /*here a is a formal parameter*/ printf("%d\n", a); } int main() { funFormal(50); } |
The output of Formal Parameters in C:
1 | 50 |