Scope of Variable in C

 The scope of a variable decides the portion of a program in which the variable can be accessed. The variable scope defines the visibility of variable in the program. Scope of a variable depends on the position of variable declaration.

A variable can be declared in three different positions and they are as follows...

  • Before the function definition (Global Declaration)
  • Inside the function or block (Local Declaration)
  • In the function definition parameters (Formal Parameters)

 
Before the function definition (Global Declaration)

Declaring a variable before the function definition (outside the function definition) is called global declaration. The variable declared using global declaration is called global variable. That global variable can be accessed by all the functions that are defined after the global declaration. That means the global variable can be accessed any where in the program after its declaration.

Example 

#include<stdio.h>
#include<conio.h>

int Num1, Num2 ;
void main(){
   void addition() ;
   void subtraction() ;
   void multiplication() ;
   Num1 = 50 ;
   Num2 = 70 ;
   printf("\n Num1 = %d, Num2 = %d", Num1, Num2) ;
   addition() ;
   subtraction() ;
   multiplication() ;
   getch() ;
}
void addition()
{
   int result ;
   result =Num1 + Num2 ;
   printf("\n Addition = %d", result) ;
}
void subtraction()
{
   int result ;
   result = Num1 - Num2 ;
   printf("\n Subtraction = %d", result) ;
}
void multiplication()
{
   int result ;
   result = Num1 * Num2 ;
   printf("\n Multiplication = %d", result) ;
}

 Output


 

Inside the function or block (Local Declaration)

Declaring a variable inside the function or block is called local declaration. The variable declared using local declaration is called local variable. The local variable can be accessed only by the function or block in which it is declared. That means the local variable can be accessed only inside the function or block in which it is declared.

 Example

#include<stdio.h>
#include<conio.h>
void main(){
    /* local variable declaration */
  int a, b;
  int c;
 
  /* actual initialization */
  a = 10;
  b = 20;
  c = a + b;
 
  printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
getch() ;
}

Output

 



In the function definition parameters (Formal Parameters)

The variables declared in function definition as parameters have a local variable scope. These variables behave like local variables in the function. They can be accessed inside the function but not outside the function.

 Example

 #include<stdio.h>
#include<conio.h>

void main(){
   void addition(int, int) ;
   int Num1, Num2 ;
   Num1 = 10 ;
   Num2 = 20 ;
   addition(Num1, Num2) ;
   getch() ;
}
void addition(int a, int b)
{
   int sum ;
   sum = a + b ;
   printf("\n Addition = %d", sum) ;

Output


 



No comments:

Post a Comment