C local block



What is a local block?

  1. Statements which are enclosed in left brace ({) and the right brace (}) forms a local Block.
  2. Local Block can have any number of statements.
  3. Branching Statements or Conditional Statements, Loop Control Statements such as  if,else,switch,for,while forms a local block.
  4. These Statements contain braces , so the portion of code between two braces would be considered a local block.
  5. Variables declared in a local block have local scope i.e they can be accessed within the block only.

Live Program : Local Scope :

#include<stdio.h>
int x = 40 ;         // Scope(Life) : Whole Program
int main()
{
int x = 10 ;         // Scope(Life) : In main
   {
   x = 30 ;
   printf("%d",x);
   }
printf("%d",x);
}

Output :

30 10

Explanation of Local Block :

  1. In the above example ,  we can see that variable ‘x’ is declared inside main function and also inside inner block.
  2. Inside inner block , local copy of variable ‘x’ is given higher priority than the outer copy of ‘x’.

Different Forms of Local Block :

Form 1 : Local Block Inside Control Statement

main()
{
if (var > 5)
    {
    printf("Inner Bock : If Statement");
    }
}

Form 2 : Local Block Inside Switch Case

switch(input) 
{
    case 1:            
         printf("Playing the game\n");
         break;
    case 2:          
        printf("Loading the game\n");
        break;
    case 3:         
        printf("Playing multiplayer\n");
        break;
    case 4:        
        printf( "Thanks for playing!\n" );
        break;
    default:            
        printf( "Bad input!\n" );
        break;
}

Similarly we can have local blocks in For Loop,While Loop and do-While Loop.