What are the local and global scope rules in C language?

CServer Side ProgrammingProgramming

Global scope

Global scope specifies that variables defined outside the block are visible up to end of the program.

Example

#include<stdio.h>
int c= 30; /* global area */
main (){
   int a = 10;
   printf (“a=%d, c=%d” a,c);
   fun ();
}
fun (){
   printf (“c=%d”,c);
}

Output

a =10, c = 30
c = 30

Local scope

Local scope specifies that variables defined within the block are visible only in that block and invisible outside the block.

Variables declared in a block or function (local) are accessible within that block and does not exist outside it.

Example

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

Output

1 2

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

Example

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

Output

1 2

The 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

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

Output

2

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

Example

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

Output

2 1
raja
Published on 08-Mar-2021 13:12:32
Advertisements