Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Global Variable in C?
2.1.
C
3.
Use of the Global Variable
3.1.
C
4.
Advantages of Global Variables
5.
Example
5.1.
C
6.
Disadvantages of Global Variables
6.1.
C
7.
Example of Using Global Variables in C
7.1.
C
8.
Frequently Asked Questions
8.1.
Can global variables be accessed by all functions in a C program?
8.2.
Are there any risks associated with using global variables?
8.3.
What is the best practice when using global variables?
9.
Conclusion
Last Updated: Apr 27, 2024
Easy

Global Variable in C

Author Rinki Deka
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In programming, variables play a crucial role in storing & manipulating data. C programming language offers different types of variables, including local & global variables. Global variables are accessible throughout the entire program, making them a powerful tool for sharing data between functions. 

Global Variable in C

This article will explore the concept of global variables in C, their uses, advantages, disadvantages, with examples to show their application.

What is a Global Variable in C?

A global variable in C is a variable that is declared outside of all functions. This location allows the variable to be accessible from any function within the code. In contrast to local variables, which are only visible within the function where they are declared, global variables are stored in a fixed location in memory & remain in existence for the duration of the program's execution.

For instance, if you declare a variable at the top of your source file, outside of any functions, that variable is considered global. It means that any function in that file can read & modify its value. Here's a simple example to illustrate:

  • C

C

#include <stdio.h>

int counter = 0; // This is a global variable

void increment() {
counter += 1; // Accesses and modifies the global variable
}

int main() {
printf("Counter: %d\n", counter);
increment();
printf("Counter: %d\n", counter);
return 0;
}

Output

Counter: 0
Counter: 1


In this code, counter is used within both the main function and the increment function. Initially, it is set to 0. After the increment function is called, its value changes to 1, demonstrating how global variables maintain their state across different parts of the program.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

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;
}

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

  • C

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;
}

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.
     
  • C

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;
}

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.

Code -: 

  • C

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;
}

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.

Frequently Asked Questions

Can global variables be accessed by all functions in a C program?

Yes, global variables are accessible from any function within the same program. They are declared outside of all function blocks, making them available throughout the entire code.

Are there any risks associated with using global variables?

Yes, using global variables can increase the risk of bugs due to their unrestricted access throughout the program. This can lead to issues with data integrity, especially in multi-threaded environments where race conditions might occur.

What is the best practice when using global variables?

The best practice is to use global variables sparingly and carefully. Consider alternative solutions like passing data through function parameters or using structures to encapsulate related data. If global variables are necessary, ensure their usage is well-documented and understood by the development team.

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 Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass