Global Variable in C
"In C programming when a variable is declared outside of a function or method is called as a global variable and when a variable declared inside a method or function is called as local variable".
Global Variable Declaration in C Programming
#include <stdio.h>
int c; /* global variable declaration */
int main () {
int a, b; /* local variable*/
a = 20;
b = 30;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
In the above program, variable c is a global variable because it is not declared inside any method of function.
Global valuable and local variables are differentiated on the basis of their scope if a variable can be accessed within only a method then it is called a local variable, and when a variable is accessed in more than one method then the variable is called a global variable.
Where to use the Global Variable?
Global variables are used according to the need, it can save time, and memory, and can decrease error possibilities, Let's know general cases where we can use the global variables.
Use of a value in Multiple Places
When a fixed value is required several times in a program then it is good to store that value in a global variable instead of a local variable, for example, we know the value of PI is 3.14 if in a program the value of pi required at several places then we can declare a global variable and we can assign the value of PI in it.