What is Global Variable and Scope in C Programming ?



Global Variable : 

  1. Global Variable is Variable that is Globally available.
  2. Scope of Global variable is throughout the program [ i.e in all functions including main() ]
  3. Global variable is also visible inside function , provided that it should not be re-declared with same name inside function because … “High Priority is given to Local Variable than Global
  4. Global variable can be accessed from any function.
#include<stdio.h>
int var=10;
void message();
void main()
{
int var=20;
  {
  int var = 30;
  printf("%d ",var); 
  }
printf("%d ",var);
message();   
}

void message()
{
printf("%d ",var);   
}

Output :

30 20 10
  • Inside message() ‘var’ is not declared so global version of ‘var’ is used , so 10 will be printed.
{  int var = 30;  printf("%d ",var);   }
  • Here variable is re-declared inside block , so Local version is used and 30 will be printed.

In Short –

  1. For Inner Block variables declared in Outer Block acts as “Global Variable“.
  2. If block contain undefined variable then –
    • It checks occurrence of that variable in outer block .
    • If it is also undefined in outer block then global version is used .
    • If it also undeclared globally then its extern definition is checked if not found then it throws error.