Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of code. Its scope is the whole program i.e. we can access the global variable anywhere in the C program after it is declared.
Example of Global Variable in C
// C program to demonstrate use of global variable
#include <stdio.h>
int x = 20; // global variable
void function1() { printf("Function 1: %d\n", x); }
void function2() { printf("Function 2: %d\n", x); }
int main()
{
function1();
function2();
return 0;
}
Output
Function 1: 20 Function 2: 20
In the above code, both functions can use the global variable as global variables are accessible by all the functions.
Note: When we have same name for local and global variable, local variable will be given preference over the global variable by the compiler.
For accessing global variable in this case, we can use the method mention here.
C Variables
A variable in C language is the name associated with some memory location to store data of different types. There are many types of variables in C depending on the scope, storage class, lifetime, type of data they store, etc. A variable is the basic building block of a C program that can be used in expressions as a substitute in place of the value it stores.