Why Global Variables are Bad in C/C++



Global variables are declared and defined outside any function in the program. They hold their values throughout the lifetime of the program and are accessible throughout its execution.

When we use our non-constant global variable in our programs, it becomes harder to manage. So, it is better to use local variables because of specific functions and easier understanding.

You can use the prefix g_ for global variable names to avoid naming conflicts and to indicate that the variable is global. There is another way to encapsulate the global variable by defining the variable static.

Therefore, these are the reasons behind global variables being bad in C/C++ programs.

Example of Global Variable bad in C/C++

In this program, you will see how the use of global variables like g_var and g_var1 creates problems because they are accessible by any function. It is hard to reuse functions as they depend on global or external variables.

C C++
#include <stdio.h>
// Non-const global variable
int g_var;        

// File-scope static global variable
static int g_var1;    

int main () {
   int a = 15;
   int b = 20;
   
   // global variable being modified
   g_var = a + b; 

   // static global variable being modified   
   g_var1 = a - b;    

   printf("a = %d\nb = %d\ng_var = %d\n", a, b, g_var);
   printf("g_var1 = %d", g_var1);

   return 0;
}

Output

The above program produces the following result:

a = 15
b = 20
g_var = 35
g_var1 = -5
#include <iostream>
using namespace std;

// Non-const global variable
int g_var;

// File-scope static global variable
static int g_var1;

int main() {
    int a = 15;
    int b = 20;

    // Modifying global variables
    g_var = a + b;
    g_var1 = a - b;

    cout << "a = " << a << "\nb = " << b << "\ng_var = " << g_var << std::endl;
    cout << "g_var1 = " << g_var1 << endl;

    return 0;
}

Output

The above program produces the following result:

a = 15
b = 20
g_var = 35
g_var1 = -5
Updated on: 2025-05-02T18:00:43+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements