Local Scope and Global Scope in C

Notes:

Local Scope and Global Scope Variables in C Programming Language:
Variable scope in C: Local scope vs global scope in C

Scope of a variable indicates the accessibility and availability (i.e. lifetime) of a variable.
A variable in C can be either in local scope or global scope

Local scope:
- Any variable declared inside a function is considered as it is in the local scope
- Local scope variable can be accessible only inside that function where it is declared
- Local scope variable will be available only during the function execution (i.e. local scope variables are created as soon as the control enters the function body and deleted as soon as the control exits the function body.)

Example Code:

#include <stdio.h>

void display();

int main()
{
int a = 10;
printf("a= %d\n",a); // a= 10
display();

return 0;
}

void display()
{
int b = 20;
printf("b= %d\n",b); // b= 20
}

Global scope:
- Any variable declared outside a function is considered as it is in the global scope
- Global scope variable can be accessible anywhere inside the program
- Global scope variable will be available throughout the program execution (i.e. global scope variables are created just before the program execution begins and deleted as soon as the program execution ends.)

Example Code:

#include <stdio.h>

void display1();
void display2();

int a = 10;

int main()
{
printf("a= %d\n",a); // a= 10
display1();
display2();
return 0;
}

void display1()
{
printf("a= %d\n",a); // a= 10
}

void display2()
{
printf("a= %d\n",a); // a= 10
}

Note: If we re-declare a global scope variable inside a local scope, then it creates another variable in the local scope.

Example Code:

#include <stdio.h>

void display();

int a = 10;

int main()
{
int a = 20;
printf("a= %d\n",a); // a= 20
display();

return 0;
}

void display()
{
printf("a= %d\n",a); // a= 10
}