What is Global Variable and Scope in C Programming ?
Global Variable :
- Global Variable is Variable that is Globally available.
- Scope of Global variable is throughout the program [ i.e in all functions including main() ]
- 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“
- 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 -
- For Inner Block variables declared in Outer Block acts as “Global Variable“.
- 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.