Back to C Programming
2025-12-295 min read

Example 1: Global Variable (C Programming)

Learn Example 1: Global Variable (C Programming) step by step with clear examples and exercises.

Why This Matters

Understanding global variables is crucial in C programming as they allow data to be shared among functions within the same file, making it easier to write and maintain complex programs. However, their use should be approached with caution due to potential side effects and difficulties in maintaining large projects.

Prerequisites

To fully grasp this lesson, you should have a good understanding of:

  • Basic C syntax (variables, data types, operators)
  • Functions in C programming
  • File handling in C
  • Understanding the concept of scope and lifetime for variables

Core Concept

Definition and Declaration

A global variable is a variable that is declared outside any function within a C file. Once declared, it can be accessed from anywhere within the same file without needing to pass it as an argument or return it as a result. Global variables are initialized to zero by default if no initial value is provided during declaration.

int global_var; // Declaration and initialization of a global variable

Scope and Lifetime

Global variables have file scope, meaning they can be accessed from any function within the same file. Their lifetime extends from the beginning of the program execution to its end.

#include <stdio.h>

int global_var = 10; // Declaration and initialization of a global variable

void func1() {
printf("Global variable value: %d\n", global_var);
}

void func2() {
printf("Global variable value: %d\n", global_var);
}

int main() {
func1();
func2();
return 0;
}

In the above example, both func1 and func2 can access the global variable global_var.

Side Effects and Code Organization

Global variables can make code more readable and easier to write when dealing with simple programs. However, they can also lead to unintended side effects and make the code harder to maintain in larger projects. It is generally recommended to use global variables sparingly and only when necessary.

Static Variables vs Global Variables

It's worth mentioning that there is another type of variable called a static variable, which has function scope instead of file scope. While they share some similarities (such as being initialized to zero by default if no initial value is provided), they behave differently in terms of lifetime and accessibility across functions.

Example: Global Variable Misuse

#include <stdio.h>

int global_var = 0; // Declaration and initialization of a global variable

void increment() {
global_var++;
}

void decrement() {
global_var--;
}

void print_value() {
printf("Global variable value: %d\n", global_var);
}

int main() {
increment();
decrement();
print_value(); // Output: 0 (unexpected result)

increment();
print_value(); // Output: 1 (still unexpected result)

return 0;
}

In the above example, increment() and decrement() functions modify the global variable global_var, but their effects are not immediately visible in print_value(). This can make the code harder to understand and debug.

Worked Example

Let's create a simple program that demonstrates the use of a global variable for storing and updating a running total.

#include <stdio.h>

int total = 0; // Declaration and initialization of a global variable

void add_number(int num) {
total += num; // Add the provided number to the global total
}

void print_total() {
printf("Total: %d\n", total); // Print the current value of the global total
}

int main() {
add_number(5);
add_number(10);
print_total(); // Output: Total: 15

return 0;
}

In this example, we have a global variable total that is initialized to zero. We also have functions add_number() and print_total() that manipulate the global variable as described in the Core Concept section.

Common Mistakes

Forgetting to Initialize Global Variables

Global variables are initialized to zero by default, but it's still a good practice to initialize them explicitly when their initial value matters.

int global_var = -1; // Initializing a global variable with an explicit value

Using Global Variables in Header Files

It is generally not recommended to declare global variables within header files, as they can lead to unintended side effects and make the code harder to maintain. Instead, consider using function prototypes and passing necessary data between functions through arguments or return values.

// Declare a function prototype in main.h
void increment_global(void);

// Implement the function in main.c
#include <stdio.h>
int global_var = 0; // Declaration and initialization of a global variable

void increment_global() {
global_var++;
}

int main() {
increment_global();
printf("Global variable value: %d\n", global_var); // Output: 1

return 0;
}

Ignoring the Impact of Global Variables on Code Readability and Maintainability

While global variables can make code easier to write in simple programs, they can also make the code harder to understand and maintain in larger projects. It is important to consider the trade-offs when deciding whether or not to use global variables.

Practice Questions

  1. Write a program that declares a global variable count and initializes it to 0. Implement functions increment(), decrement(), and print_value() to manipulate the global variable as described in the Core Concept section. Test your implementation by calling these functions from within main().
  2. Modify the program from Practice Question 1 to include a function reset() that sets the global variable count back to 0. Test your implementation by calling reset(), increment(), and decrement() functions from within main().
  3. Write a program that uses a global variable total to calculate the sum of an array of integers passed as an argument to a function calculate_sum(). Test your implementation by calling calculate_sum() from within main().

FAQ

Q: Why are global variables considered bad practice in larger projects?

A: Global variables can lead to unintended side effects, make the code harder to understand and maintain, and increase the risk of bugs. It is generally recommended to use them sparingly and only when necessary.

Q: Can I declare a global variable within a header file?

A: While it's technically possible to declare a global variable within a header file, it is generally not recommended due to potential unintended side effects and increased difficulty in maintaining the code. Instead, consider using function prototypes and passing necessary data between functions through arguments or return values.

Q: How can I ensure that my global variables are initialized with explicit values?

A: To ensure that your global variables are initialized with explicit values, declare and initialize them at the beginning of the C file where they are defined. This will help make the code more readable and reduce the risk of bugs caused by uninitialized variables.