C Language

Local and Global Variables

In C Language by Baqir AliLeave a Comment

There are many types of variables but here we will only discuss two of them, local and global variables.

Local Variables

A variable that is defined inside the body of any function. Local variables are only used within that function and can not be accessed outside of that function.

#include<stdio.h>
void main(void)
{
   int a;
   a=10;
   printf("The value of a is %d",a);
}

In the above example, ‘a’ is a local variable. The variable ‘a’ can not be used or accessed outside of the main function.

Global Variables

A global variable is declared globally so it is available to all functions. A global variable declaration looks normal but is located outside any of the program’s functions. This is usually done at the beginning of the program file but after preprocessor directives. The variable is not declared again in the body of the functions which access it

#include<stdio.h>
int a; 
void display(void)
{
    a++;
}
void main(void)
{
   a=10;
   display();
   printf("The value of a is %d",a);
} 

Output is:

The value of a is 11

In the above example, a is defined globally after preprocessor directives. Here variable ‘a’ is available to all functions and can be accessed via all functions.

Get The Coding Examples From C Language Code Example Page

Local and Global Variable

Support us by sharing this post

Leave a Comment