Scope of Variables

Scope of Variables : 

  • Scope of a variable is a part of program or location in a program from where we can access that variable.
  • It can either local or global.
1) Local Scope : 
  • Variables which are declared inside a function are local variables to that function and they have local scope. 
  • Meaning such a variables are accessible only within that function.
  • Such a variables can not accessed from outside of a function.
  • Example : Consider following code
#include<stdio.h>
int main()
{
  int a=20;
  void add()
  {
     int sum;
      sum = a + 10;
      printf("Sum inside function : %d",sum);
   }
   add();
   printf("Sum outside function : %d",sum);
  return 0;
}

Output :

main.c:13:38: error: ‘sum’ undeclared (first use in this function)
print("Sum outside function : %d",sum);



Explanation : Output is error because sum is local variable of function add() and we can not access it outside add() as did in program. 

Let's redeclare variable outside add() and see what happens


#include<stdio.h>
int main()
{
  int a=20,sum=0;
  void add()
  {
     int sum;
      sum = a + 10;
      printf("Sum inside function : %d",sum);
   }
   printf("Sum outside function : %d",sum);
  return 0;
}

Output :

Sum inside function : 30
Sum outside function : 0


Note : Since variable a is declared inside function it can be accessed from any part inside main(). Also we can identify difference between local variable values.

2) Global Scope : 
  • Variables declared outside the main function at the top of a program are called global variables and can be accessed throughout the program or from any part of whole program.
  • Default value for global variable is zero if they are of type integer.
  • Example : Let's do above program by making sum a global variable

  #include<stdio.h>
  int sum;
  int main()
{
  int a=20;
  void add()
  {
      sum = a + 10;
      printf("Sum inside function : %d",sum);
   }
   printf("Sum outside function : %d",sum);
  return 0;
}

Output :

Sum inside function : 30
Sum outside function : 30


Note : Since sum is global variable no need to redeclare it in function add().  Also its value is maintained throughout the program. 

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.