Why are global variables bad in C/C++?

C++ProgrammingServer Side Programming

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

Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.

Use ‘g_’ as prefix of the variable name to avoid the naming collisions and for knowledge that variable is global. There is another way also that encapsulate the global variable by making variable static.

Here is an example of global variables in C language,

Example

 Live Demo

#include <stdio.h>
int g_var;
static g_var1;

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

   g_var = a+b;
   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

Here is the output

a = 15
b = 20
g_var = 35
g_var1 = -5
raja
Published on 24-Oct-2018 09:03:08
Advertisements