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

We define local variables within the body of any function or class. We use local variables 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

We declare a global variable 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.

Local and Global Variable

Support us by sharing this post

About the Author

Baqir Ali

Facebook Twitter

Hi, I am Baqir Ali ---- Blogger, Programmer, and a Teacher. I am currently working as a Programmer for Softnat Technologies. I have tons of ideas and data to share with you all via blogging.

Leave a Comment