Explain the scope rules related to the statement blocks in C language

CServer Side ProgrammingProgramming

The scope rules are related to the following factors −

  • Accessibility of a variables.
  • Period of existence of a variable.
  • Boundary of usage of variables.

Scope rules related to statement blocks are given below −

  • Block is enclosed in curly braces which consists of set of statements.

  • Variables declared in a block are accessible and usable within that block and does not exist outside it.

Example 1

Following is the C program for scope rules related to statement blocks 

 Live Demo

#include<stdio.h>
main ( ){
   {
      int i = 1;
      printf ("%d",i);
   }
   {
      int j=2;
      printf("%d",j);
   }
}

Output

The output is stated below −

1 2

Even if the variables are redeclared in their respective blocks and with the same name, they are considered differently.

Example 2

Here is another C program for scope rules related to statement blocks

 Live Demo

#include<stdio.h>
main ( ){
   {
      int i = 1;
      printf ("%d",i);
   }
   {
      int i =2;
      printf ("%d",i);
   }
}

Output

The output is stated below −

1 2

Redeclaration of variables within the blocks bearing the same names as those in the outer block masks the outer block variables, while executing the inner blocks.

Example 3

Here is another C program for scope rules related to statement blocks

 Live Demo

#include<stdio.h>
main ( ){
   int i = 1;{
      int i = 2;
      printf ("%d",i);
   }
}

Output

The output is stated below −

2

Variables declared outside the inner blocks are accessible to the nested blocks, provided these variables are not declared within the inner block.

Example 4

Consider another program for scope rules related to statement blocks

 Live Demo

#include<stdio.h>
main ( ){
   int i = 1;{
      int j = 2;
      printf ("%d",j);
      printf ("%d",i);
   }
}

Output

The output is stated below −

2 1
raja
Published on 11-Mar-2021 12:27:40
Advertisements