When to use Global variables in C?
Global variables in C are variables that are defined outside of any function and are accessible from any function within the same file or other files if declared with the extern keyword. While their use is often discouraged due to potential issues with maintainability, debugging, and testing, there are specific scenarios where using global variables can be appropriate:
- Shared Data Across Functions: When multiple functions need to access and modify the same data, a global variable can be a convenient way to share that data without having to pass it as an argument to each function.
- Constants Across Application: For defining constants that need to be accessed by multiple functions across different files, global variables can be used effectively, although const qualifiers should be used to make sure these variables are not modified accidentally.
- Configuration or State Information: Global variables can be useful for storing application-wide configuration settings or state information that needs to be accessed by multiple parts of the program. This allows different components to check or modify the state as needed.
- Reducing Function Call Overhead: In performance-critical applications where passing large amounts of data to functions repeatedly may cause a significant overhead, global variables might be used to make this data accessible to all functions without the cost of passing it around.
- Simplicity in Small Programs: In very small, simple programs or scripts where the disadvantages of global variables (such as difficulty in tracking their changes across different parts of the program) are less likely to cause problems, using global variables can lead to quicker development times.
Use of the Global Variable
-
Sharing Data Across Functions: When multiple functions need to access or modify the same data, global variables provide a convenient way to share this data without the need to pass it around as parameters.
-
Maintaining State Information: In applications where certain state information must be maintained throughout the program's execution, global variables offer a straightforward solution. For example, they can track the state of a system in embedded programming.
-
Configuration Settings: Global variables can hold configuration settings that need to be accessed by various parts of a program. These settings might include system flags, operation modes, or user settings.
Here is an example which shows the use of global variables for maintaining state information in a simple application:
C
#include <stdio.h>
int loginStatus = 0; // Global variable to track user login status
void logIn() {
loginStatus = 1; // User is logged in
printf("User logged in successfully.\n");
}
void logOut() {
loginStatus = 0; // User is logged out
printf("User logged out successfully.\n");
}
int main() {
printf("Initial login status: %d\n", loginStatus);
logIn();
printf("Login status after logging in: %d\n", loginStatus);
logOut();
printf("Login status after logging out: %d\n", loginStatus);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Initial login status: 0
User logged in successfully.
Login status after logging in: 1
User logged out successfully.
Login status after logging out: 0
In this example, the loginStatus global variable is used to track whether a user is logged in (1) or logged out (0). This variable is accessed and modified by the logIn and logOut functions to update the user's status accordingly.
Advantages of Global Variables
-
Simplicity: Using global variables simplifies code, especially when multiple functions need to access or modify the same data. This avoids the complexity of passing multiple arguments to functions and managing them.
-
Memory Efficiency: Global variables are allocated once and exist throughout the life of the program, which can be more memory efficient compared to repeatedly allocating and deallocating local variables if the data needs to persist between function calls.
-
State Preservation: They naturally preserve state across function calls without any extra mechanism. This can be particularly useful in situations where you need to keep track of operational states or configuration settings that should not reset every time a function is called.
-
Cross-Function Communication: Global variables facilitate communication between functions without the need for complex function interfaces or data structures. This can reduce the effort required for function design and interaction.
- Ease of Use in Callbacks and Interrupts: In programming contexts such as event-driven software or interrupt-driven programming, global variables provide an easy way to share and modify data between the main program and the interrupt service routines or callback functions.
Example of advantages of global variable
C
#include <stdio.h>
int operationCount = 0; // Global variable to count the number of operations performed
void performOperation() {
operationCount++; // Increment the count each time an operation is performed
printf("Operation %d performed\n", operationCount);
}
int main() {
performOperation();
performOperation();
performOperation();
printf("Total operations performed: %d\n", operationCount);
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Operation 1 performed
Operation 2 performed
Operation 3 performed
Total operations performed: 3
In this example, the global variable operationCount is used to keep track of the number of operations performed throughout the program's execution. It showcases how global variables can effectively manage state without needing to pass around or reset counters.
Disadvantages of Global Variables
-
Increased Risk of Bugs: Global variables can be modified from anywhere in the program, making it difficult to track down where changes are made. This can lead to bugs that are hard to diagnose and fix, especially in large codebases.
-
Tight Coupling: Functions that rely on global variables are inherently coupled to these variables. This coupling makes the code less modular and harder to reuse, as the functions depend not only on their parameters but also on the external state defined by the global variables.
-
Testing Difficulties: Automated testing becomes more challenging when functions depend on global variables. Since global variables maintain state across function calls, tests may need to reset these variables to ensure each test starts with a clean state, adding complexity to test setups.
-
Concurrency Issues: In multi-threaded applications, global variables can lead to concurrency problems such as race conditions, where multiple threads modify the variable simultaneously. This can result in inconsistent data and unpredictable behavior.
- Difficulty in Managing Scope: Global variables are accessible throughout the entire program, which can lead to unintended interactions between different parts of the code. It's also easy to create naming conflicts, especially in larger projects where many developers might unwittingly create global variables with the same name.
Example of disadvantages of global variable
C
#include <stdio.h>
int sharedResource = 0; // Global variable used by multiple functions
void incrementResource() {
sharedResource++; // Potential race condition if called from multiple threads
printf("Resource incremented to %d\n", sharedResource);
}
void decrementResource() {
sharedResource--; // Potential race condition if called from multiple threads
printf("Resource decremented to %d\n", sharedResource);
}
int main() {
incrementResource();
decrementResource();
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Resource incremented to 1
Resource decremented to 0
In this code, both incrementResource and decrementResource modify the sharedResource global variable. If these functions are called from different threads, they may interfere with each other, leading to incorrect updates and a final value that might not reflect the actual number of increments and decrements performed.
Example of Using Global Variables in C
Consider a program that calculates the average score of all students in a class. We will use a global variable to keep track of the total score and the number of scores entered, which allows us to calculate the average whenever needed without passing these values between functions.
C
#include <stdio.h>
int totalScore = 0; // Global variable for the total score accumulated
int count = 0; // Global variable for the number of scores entered
void addScore(int score) {
totalScore += score; // Add the given score to the global totalScore
count++; // Increment the global count of scores
}
double calculateAverage() {
if (count == 0) return 0; // Avoid division by zero
return (double) totalScore / count; // Calculate & return the average score
}
int main() {
addScore(85);
addScore(90);
addScore(78);
printf("Average score: %.2f\n", calculateAverage()); // Output the average score
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output
Average score: 84.33
Explanation :
-
Global Variables: totalScore and count are declared as global variables. This means they are accessible throughout the entire program, including within the addScore and calculateAverage functions.
-
Function addScore: This function takes an integer score as an input and adds it to the totalScore. It also increments count by one. Since totalScore and count are global, they retain their values even after the function completes.
- Function calculateAverage: Calculates the average by dividing totalScore by count. It checks if count is zero to avoid division by zero, providing a simple error handling mechanism.
How to Access Global Variable if there is a Local Variable with Same Name in C?
In C programming, if you have both a global variable and a local variable with the same name within the same scope, the local variable will hide or shadow the global variable. This means that any reference to the variable name within the scope will point to the local variable, not the global one. However, you can still access the global variable from within the function where it's shadowed using a few different methods.
Example:
#include <stdio.h>
int value = 5; // This is the global variable
void function() {
int value = 10; // This is the local variable with the same name
printf("Local value: %d\n", value); // This will print 10
// To access the global variable when a local variable of the same name exists:
printf("Global value: %d\n", ::value); // This will print 5 in C++
}
int main() {
function();
return 0;
}

You can also try this code with Online C Compiler
Run Code
The code above won't compile in standard C because C does not support the :: operator to access global variables like C++. However, the example illustrates the typical problem. In C, to work around this, you would typically need to rename one of the variables or refactor the code.
Let's see how you could modify the example to access both variables in C:
#include <stdio.h>
int globalValue = 5; // Renamed global variable for clarity
void function() {
int localValue = 10; // Local variable
printf("Local value: %d\n", localValue); // This will print 10
printf("Global value: %d\n", globalValue); // This will print 5
}
int main() {
function();
return 0;
}

You can also try this code with Online C Compiler
Run Code
Alternative Approach
If renaming is not an option (for instance, in a large codebase where the global variable is widely used), another approach would be to use a function or another mechanism to access the global variable.
For example:
#include <stdio.h>
int value = 5; // Global variable
int getGlobalValue() {
return value;
}
void function() {
int value = 10; // Local variable
printf("Local value: %d\n", value); // Prints the local value
printf("Global value: %d\n", getGlobalValue()); // Accesses the global via a function
}
int main() {
function();
return 0;
}

You can also try this code with Online C Compiler
Run Code
In this last example, getGlobalValue() encapsulates access to the global variable, ensuring that local changes to the naming scope do not affect the ability to retrieve the global variable's value. This can be very useful in more complex applications where scope management is crucial.
Frequently Asked Questions
Which is a global variable?
A global variable in C is defined outside of all functions, typically at the top of the source file, making it accessible throughout the program.
What is the global section in C?
The global section in C refers to the part of a program where global variables and functions are defined, and accessible by any part of the program.
What is a local variable in C?
A local variable in C is defined within a function or block and is only accessible within that function or block, limiting its scope and lifetime.
Conclusion
In this article, we have learned about global variables in C, their uses, advantages, and disadvantages, along with a practical example. Global variables provide a convenient way to share data across different functions within a program, making them useful for maintaining state and configuration settings. However, their unrestricted access can also lead to complex bugs and difficulties in managing program state, particularly in larger or multi-threaded applications.
You can refer to our guided paths on the Code360 You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.