Scope of global variable



In this tutorial we will be learning about the Scope of global variable in c programming. How global variable is accessed in complete program is explained using simple example.

Scope of global variable

#include<stdio.h>
int num = 100 ; // Global
void func(); // Prototype
int main()
{
    int num = 20;  // Local to main
    { 
    int num = 30 ;  // Local to Inner Part
    printf("%d ",num);
    func();
    }
 printf("%d ",num);
 return(0);
}
void func()
{
 printf("%d ",num);
}

Output :

 30 100 20

Explanation : Scope of the Variable

In the above program we have total three copies of same variable. We have 3 copies of the variable num. Below is the list of all copies of variable in program -

Copy of variable Statement
Global copy of variable int num = 100;
Local copy of variable in main function int num = 20;
Local copy of variable inside block int num = 30;

Local Variable copy

We know that global variable can be accessed using the complete program. If same variable is declared inside the scope where global variable is accessible then priority will be given to local variable

{
int num = 30 ;  // Local to Inner Part
printf("%d ",num);
func();
}

in the above inner block, priority is given to the local variable i.e 30. If we remove the following declaration line then output printed would be 20

Scope of global variable

Local Function Variable

function is written outside the main function. So in this case only global copy will be accessible not the one which is declared inside the main so it would print 100

void func()
{
printf("%d ",num);
}

after calling the above function from inner block we can have access to the global copy of variable since we don’t have local copy of variable.

Outside Inner block copy

printf("%d ",num);
return(0);

after moving out from the inner block, we again have access to the local copy from main function.