Open In App

Can Global Variables be dangerous ?

In a small code, we can track values of global variables. But if the code size grows, they make code less understandable (hence less maintainable). It becomes difficult to track which function modified the value and how.




// A C++ program to demonstrate that a
// global variables make long code less
// maintainable.
 
int c = 1;
 
int fun1()
{
   // 100 lines of code that
   // may modify c and also
   // call fun2()
}
 
void fun2()
{
   // 100 lines of code that
   // may modify c and also
   // call fun1()
}
 
void main()
{
    // 1000 lines of code
 
    c = 0;
 
    // 1000 lines of code
 
    // At this point, it becomes difficult
    // to trace value of c
    if (c == 1)
        cout << "c is 1" << endl
    else
        cout << "c is not 1 << endl
}

Article Tags :