What is a Variable in C?
A variable is nothing but a name for a memory location. A variable also called an identifier, has a range and scope according to the data type it is mentioned for. Every variable has a data type associated with specifying the range, size, etc.
In C, there are majorly three variables based on the scope: local, static, and global. 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 declared outside of any block or function. Now let us dive deep into the meaning of global variables in C.
What is Global Variable in C?
As the name suggests, the scope of the global variable is global, or any program member can access it. On the other hand, a local variable has local scope. The global variable in C is an important part of the GATE exam. The default value of a global variable in C is set to zero(0).
Global Variable in C Definition
A global variable in C is defined as one that is declared outside of any block or function. Any function and number of times can change the value of a global variable in the C programming language. Its value can be altered and reused many times.
Use of Global Variables in C
As we have discussed the definition of global variables, we now know they are useful. 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 often as required, and they are available for use for the entire lifetime of the program.
Syntax and Example of Global Variable in C
The syntax of a global variable is the same as any other variable declaration in C. A question can be formulated in the GATE question paper. 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