Global variables in C
Global Variables (external variables)
Global variables in C are created when the program starts and remain in memory until the program ends.
They are declared outside of any function/block and are accessible from any function within the same file.
They are not destroyed when a function returns, and their values can be accessed and modified by any function in the program.
Global variables are also known as external variables.
Global variables are often used to store values that are shared by multiple functions, such as constant values, or values that persist across multiple function calls.
Global Variables - Example
#include <stdio.h>
int count;
void increment_count()
{
count++;
printf("The value of count is %d\n", count);
}
int main()
{
count = 0;
increment_count();
increment_count();
return 0;
}
Output:
Example
- The variable
count
is a global variable that is declared outside of any function. It can be accessed and modified from within any function, including theincrement_count
function and themain
function.
Global variables are stored in a region of memory called the data segment, which is separate from the stack where local variables are stored.
When to use Global variables
Global variables should be used in situations where the variable needs to be accessible from multiple functions or where the variable needs to persist across multiple function calls.
Some common use cases for global variables include:
Sharing data between functions: Global variables can be used to share data between functions. For example, a global variable can be used to store a shared counter that is incremented by one function and read by another.
Constants: Global variables can be used to store constant values that are used by multiple functions. For example, a global variable can be used to store the value of
Pi
that is used by multiple functions to perform mathematical operations.Inter-file communication: When writing programs that span multiple files, global variables can be used to communicate between files. For example, a global variable can be used to store a shared data structure that is updated by one file and read by another.
Persistent data: Global variables can be used to store data that needs to persist across function calls. For example, a global variable can be used to store the current state of a program that is read and updated by multiple functions.
Use of global variables should be minimized in most cases to promote modularity, maintainability, and to reduce the risk of unintended interactions between functions.
Instead, it's usually better to pass data between functions as arguments or to return data from functions as return values.