Home  >  Article  >  Backend Development  >  Explain the scoping rules related to statement blocks in C language

Explain the scoping rules related to statement blocks in C language

WBOY
WBOYforward
2023-09-11 12:53:10683browse

Explain the scoping rules related to statement blocks in C language

Scope rules are related to the following factors −

  • Accessibility of variables.
  • The existence period of the variable.
  • Usage boundaries of variables.

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.

Example 1

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);
   }
}

Output

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.

Example 2

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);
   }
}

Output

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.

Example 3

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);
   }
}

Output

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.

Example 4

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete