Home > Article > Backend Development > Explain the scoping rules related to statement blocks in C language
Scope rules are related to the following factors −
The scope rules related to statement blocksare as follows −
Statement blocks are enclosed by curly braces and contain a set of statement.
Variables declared in a statement block can be accessed and used within the block, but do not exist outside the block.
The following is a C program related to Scope rules related to statement blocks −
Demonstration
#include<stdio.h> main ( ){ { int i = 1; printf ("%d",i); } { int j=2; printf("%d",j); } }
The output is as follows −
1 2
Even if variables are redeclared in their respective code blocks and use the same name, they are considered different.
The following is another C program about statement block scope rules-
Real-time demonstration
#include<stdio.h> main ( ){ { int i = 1; printf ("%d",i); } { int i =2; printf ("%d",i); } }
The output is as follows −
1 2
Redeclaring a variable inside a block with the same name as the outer block masks the outer block variable, which happens when the inner block is executed.
This is another C program about scope rules related to statement blocks−
Real-time demonstration
#include<stdio.h> main ( ){ int i = 1;{ int i = 2; printf ("%d",i); } }
The output is as follows −
2
Variables declared outside the inner block can be accessed in the nested block, provided that these variables are not declared in the inner block.
Consider another program with scoping rules associated with statement blocks:
Demonstration
#include<stdio.h> main ( ){ int i = 1;{ int j = 2; printf ("%d",j); printf ("%d",i); } }
Output As follows −
2 1
The above is the detailed content of Explain the scoping rules related to statement blocks in C language. For more information, please follow other related articles on the PHP Chinese website!