What is a Variable?
A variable is nothing but a name for a memory location. A variable also called an identifier, has the range and scope according to the data type it is mentioned for. Every variable has a data type associated with it to specify the range and size, etc.
In C, there are majorly three types of variables based on the scope they are local variables, static variables, and global variables. A local variable has local scope within the block it is declared in. A static variable creates memory at the compile time and retains its value throughout the program execution. A global variable is one that is declared outside of any block or function. Now let us dive deep into the meaning of global variables in C.
Define a Global Variable in C?
A global variable in C is defined as one that is declared outside of any block or function. The value of a global variable can be changed by any function and any number of times. Its value can be altered and reused many times.
As the name itself suggests, the scope of the global variable is global, or it can be accessed by any member of the program. On the other hand, a local variable has local scope. A global variable is declared usually just before the main function. The default value of a global variable in C is set to zero(0).
Use of Global Variables in C
As we have discussed the definition of global variables, we now know that they are of great use. We define a global variable at the very top of the program. These variables hold their value throughout the lifetime of the program.
Any block or function in the program can access the global variables. This means that once declared, we can use global variables as many times as required, and they are available for use for the entire lifetime of the program.
Syntax and Example for Global Variable in C
The syntax of a global variable is the same as any other variable declaration in C. That is data_type followed by the variable_name;
Example: int value;
However, the global variables are declared outside of any block or function. It is declared just before the main function of the program. The declaration of the global variable will be clear by seeing the following example:
int value=9;
#include<stdio.h>
void main()
{
printf(“%d”, value);
return 0;
}
Output: 9
Comments
write a comment