Global Variable in C: How to Declare, Scope, and Practical Examples

Updated on September 14, 2024

Article Outline

When we first dive into C programming, one of the terms that pops up is “global variables.” But what exactly is the global variable in C? Why are they so very important?

 

Suppose we are writing a program composed of a lot of functions, all of which need access to the same dataset. How could we accomplish this task without explicitly passing the data?

 

That’s where the global variable for C becomes handy.

 

Global variables are declared outside of any function. Any function in the program can then access a global variable. Sometimes, this really comes in very handy, as it enables us to share information between different parts of our program.

How to Declare and Initialise the Global Variable in C

Declaring a global variable in C is simple.

 

We place the declaration outside of all functions, usually at the very top of our program. This way, every function in the program can see and use it.

 

Here’s a simple example:

#include <stdio.h> // Declaring a global variable int counter = 0; int main() { counter++;  // Incrementing the global variable printf("Counter: %dn", counter); return 0; }

 

Output:

Counter: 1

 

In this code, counter is a global variable. It’s available to every function in the program, not just main.

 

But what if we don’t initialise it?

 

By default, global variables in C are initialised to zero. So, if we declared int counter without assigning a value, it would start at 0.

 

Global variables can be of any data type—int, float, char, you name it. And we can initialise them just like any other variable. But here’s where it gets interesting.

 

What happens if we need the user to input a value? Let’s tweak our example:

#include <stdio.h>  // Declaring a global variable int userValue;  int main() { printf("Enter a number: "); scanf("%d", &userValue);  // Taking input from the user  printf("You entered: %dn", userValue); return 0; }

 

Output:

Enter a number: 7 You entered: 7

 

Now, userValue is a global variable that takes input directly from the user. This value is then available to every function that follows.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Understanding the Scope and Lifetime of the Global Variable in C

Now that we have covered the declaration and usage of global variables, we will go further to discuss their scope and lifetime.

 

This way, every global variable that is declared exposes itself to the global scope and can thus be available under any function in the file.

 

In C programming, global variables live throughout the program from start to end, whereas local variables only live within the functions they belong to. This can be a blessing and a curse all rolled into one.

 

This has the advantage that we needn’t worry so much about losing our data, but it also requires more carefulness in how and when we make our changes.

 

Consider this example:

#include <stdio.h> // Global variable declaration int total; void addToTotal(int num) { total += num; } int main() { total = 10;  // Initializing the global variable addToTotal(5);  // Adding 5 to total printf("Total: %dn", total); return 0; }

Output:

Total: 15

In this code, total is accessible to both main and addToTotal. This allows us to modify the total from anywhere in the program.

 

But here’s the catch: since total persists for the entire runtime, any change we make sticks around. If one function messes up the value, it can cause problems down the line.

Accessing and Modifying Global Variables Across Multiple Functions

Global variables are powerful; they can be referred to and changed by any function of a program.

 

It does, however, open up the potential to create problems.

 

Suppose that we have lots of functions, each of which needs to access the same variable.

#include <stdio.h> // Global variable declaration int sharedVar = 0; void increment() { sharedVar++; } void decrement() { sharedVar--; } int main() { printf("Initial value: %dn", sharedVar); increment();  // Increment the global variable printf("After increment: %dn", sharedVar); decrement();  // Decrement the global variable printf("After decrement: %dn", sharedVar); return 0; }

Output:

Initial value: 0 After increment: 1 After decrement: 0

In this example, both increment and decrement functions modify sharedVar.

 

Let’s take that to a slightly more complex example, where you have two functions that are updating a global variable repeatedly. Without careful management, it is quite possible to lose track of what is going on.

 

That is when bugs slip in, thus making the code pretty hard to debug and maintain.

 

Consequently, this makes global variables highly attractive for use in maintaining a clean, organised code base.

 

We should always know which functions modify which variables and why. This helps us avoid unexpected changes and makes our program easier to maintain.

Redeclaring and Using the extern Keyword with Global Variables

When working with the global variable in C, one question often comes up:

 

What if we wanted to use the same global variable in more than one file when making a project? Or what happens if a variable with the same name is declared by accident in a local scope?

 

This is where the extern keyword comes in handy.

 

extern is like a bridge between different parts of your program.

 

It tells the compiler that a global variable exists somewhere, but it’s not being defined here. Instead, we’re just letting the compiler know that it should look elsewhere for the definition.

 

Let’s see how this works.

 

Imagine we have two files in our project, main.c and utils.c. We want to use a global variable, sharedCount, in both files.

 

Here’s what main.c might look like:

#include <stdio.h>   // Declaring the global variable int sharedCount = 5; void printCount(); int main() { printf("In main.c, sharedCount = %dn", sharedCount); printCount();  // Calling the function in utils.c return 0; }

And here’s utils.c:

#include <stdio.h>  // Telling the compiler that sharedCount exists extern int sharedCount;  void printCount() { printf("In utils.c, sharedCount = %dn", sharedCount); }

In utils.c, we use extern int sharedCount; to let the compiler know that sharedCount is defined somewhere else, specifically in main.c.

 

When we compile and run the program, the output looks like this:

In main.c, sharedCount = 5 In utils.c, sharedCount = 5

This shows how extern allows us to share global variables across different files. It’s a powerful tool, but we need to use it carefully.

 

Why? Because if we’re not careful, using extern can make our code harder to debug.

 

Suppose we forget to declare sharedCount in main.c. The program might compile, but it could behave unpredictably, leading to hours of frustrating debugging.

Best Practices for Using Global Variable in C Programming

Global variables are useful, but they can also be tricky. We need to manage them carefully to avoid problems.

 

Here are some best practices to keep in mind when working with the global variable in C.

1. Limit the Use of Global Variables

The advisable thing to do is to use the global variables only when they are completely inevitable.

 

Why?

 

Because global variables are accessible from anywhere in your program, it’s pretty easy to accidentally mess with their value.

 

This can result in bugs that may take a lot of time to solve or identify in the first place. If possible, then you should always prefer to use local variables.

 

Local variables can only be accessed in the function where it was declared, and hence, there are fewer chances of having unforeseen consequences.

2. Name Global Variables Clearly

Naming matters, especially for global variables.

 

A clear, descriptive name helps us and others understand what the variable is for. Avoid generic names like x or temp. Instead, use names that describe the variable’s purpose, like totalSales or userCount.

 

This makes the code easier to read and maintain.

3. Use Constants for Unchanging Global Variables

If a global variable’s value shouldn’t change, declare it as a constant. This prevents any function from

#include <stdio.h> const int maxUsers = 100; int main() { printf("Max users allowed: %dn", maxUsers); return 0; }

Output:

Max users allowed: 100

Here, maxUsers is a constant global variable. It’s available to every function, but its value can’t be changed. This adds an extra layer of safety to our code.

4. Group Related Global Variables Together

If we have several global variables related to the same feature, group them together in a structure.

 

This helps keep our code organised and makes it easier to manage related variables.

 

By grouping related variables into a struct, we can keep our code tidy and make it easier to work with.

#include <stdio.h> struct Config { int screenWidth; int screenHeight; int colourDepth; }; struct Config settings = {1024, 768, 32}; int main() { printf("Screen width: %dn", settings.screenWidth); printf("Screen height: %dn", settings.screenHeight); printf("Colour depth: %d-bitn", settings.colourDepth); return 0; }

Output:

Screen width: 1024 Screen height: 768 Colour depth: 32-bit

5. Document Global Variables Thoroughly

Global variables affect the entire program, so it’s important to document them clearly.

 

Include comments explaining what the variable is for, where it’s used, and any important details about its lifecycle. This helps future developers (and your future self) understand how the variable fits into the program.

 

Good documentation makes our code easier to read, understand, and maintain.

#include <stdio.h> // This global variable tracks the number of users currently online. // It is incremented in the login function and decremented in the logout function. int onlineUsers = 0; int main() { // Code to manage user logins and logouts return 0; }

Common Mistakes to Avoid When Working with Global Variables

Accidental Modification:

 

  • Global variables can be changed by any function, leading to unintended consequences.
  • Example: A global variable tracking items in a cart might be accidentally incremented twice, causing system inconsistencies.
  • Hard to spot errors, especially in larger programs.

 

Name Conflicts:

 

  • Poorly named global variables can conflict with local variables, causing bugs.
  • Avoid using generic names like count or temp; choose clear, descriptive names.

 

Overuse of Global Variables:

 

  • Over-reliance on global variables can make code hard to understand and maintain.
  • Limit the use of global variables to essential cases to avoid “spaghetti code.”

 

Lack of Documentation:

 

  • Failing to document global variables can lead to confusion, especially for future developers.
  • Include comments explaining the purpose, usage, and details of each global variable.

 

Ignoring Thread Safety:

 

  • In multi-threaded programs, global variables can cause race conditions, leading to unpredictable behaviour.
  • Use synchronisation techniques like mutexes to control access in multi-threaded environments.

Real World Examples of Global Variable in C

Example 1: Tracking the Number of Active Users

Consider we’re building a basic chat application. We need to keep track of how many users are currently online.

 

A global variable is perfect for this. Here’s how we might do it:

 

#include <stdio.h> // Global variable to track the number of active users int activeUsers = 0; void userLogin() { activeUsers++;  // Increment the count when a user logs in printf("User logged in. Active users: %dn", activeUsers); } void userLogout() { activeUsers--;  // Decrement the count when a user logs out printf("User logged out. Active users: %dn", activeUsers); } int main() { userLogin(); userLogin(); userLogout(); return 0; }

Output:

User logged in. Active users: 1 User logged in. Active users: 2 User logged out. Active users: 1

Here, the activeUsers variable is shared between userLogin() and userLogout(). Each function can modify it, keeping the count accurate throughout the program’s runtime.

 

This approach is simple but effective for scenarios where multiple functions need to access and update the same data.

Example 2: Storing Configuration Settings

Global variables can also be handy for storing settings that are used across multiple functions.

 

Consider a program that needs to handle different screen resolutions. Instead of passing these settings around, we can store them globally:

#include <stdio.h> // Global variables for screen settings int screenWidth = 1920; int screenHeight = 1080;   void displaySettings() { printf("Screen Width: %dn", screenWidth); printf("Screen Height: %dn", screenHeight); }   int main() { displaySettings(); return 0; }

Output:

Screen Width: 1920 Screen Height: 1080

 

Here, screenWidth and screenHeight are global variables that hold the screen resolution.

 

Any function can access these settings, making it easy to manage and update them without passing variables around.

Example 3: Sharing Data Between Functions

At times, one may need to share data across different functions performing completely unrelated tasks.

 

Suppose we are implementing something like a program for computing areas of various shapes. One may think of storing the results of such calculations using global variables:

 

#include <stdio.h> // Global variables to store calculation results double rectangleArea; double circleArea; void calculateRectangleArea(double width, double height) { rectangleArea = width * height; }   void calculateCircleArea(double radius) { circleArea = 3.14159 * radius * radius; }   int main() { calculateRectangleArea(5.0, 3.0); calculateCircleArea(2.5);   printf("Rectangle Area: %.2fn", rectangleArea); printf("Circle Area: %.2fn", circleArea);   return 0; }

Output:

Rectangle Area: 15.00 Circle Area: 19.63

In this code, rectangleArea and circleArea are global variables that store the results of the area calculations.

Conclusion

Global variable in C can be a powerful tool in programming. They make it easy to share data across functions and keep track of important values throughout the life of your program.

 

But they come with challenges, like accidental modifications, name conflicts, and potential issues in multi-threaded environments.

 

To use global variables effectively, focus on clear naming, careful documentation, and limiting their use to essential cases. Understand the risks and implement best practices to maintain clean, manageable code.

 

When handled correctly, global variables can enhance your program’s efficiency and structure.

FAQs
No, global variables must be declared outside any function. If it is declared inside a function, the variable will be scoped only for that specific function.
In its default state, a global variable is initialised to zero.
To share a global variable among different files, it has to be declared in one file using extern for the other files. This tells the compiler that the variable exists and is defined elsewhere.
Yes, any function in the program can modify a global variable.

Updated on September 14, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved