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 CPP 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 } |
chevron_right
filter_none
- In above code, we notice one of the biggest problem of global variable that is Debugging. It means if we trying to figure out where that variable c has changed between thousands of lines of code is very difficult job.
- In multihreaded environment a global variable may change more than once (in different execution orders) and cause more problems.
- Global variables are generally used for constants. Using them for non-const values is not recommended.
Recommended Posts:
- Initialization of global and static variables in C
- Redeclaration of global variable in C
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Can we access global variable if there is a local variable with same name?
- Variables in C++
- Static Variables in C
- Variables and Keywords in C
- Scope of Variables in C++
- Constants vs Variables in C language
- Templates and Static variables in C++
- Initialization of static variables in C
- Operations on struct variables in C
- Implicit initialization of variables with 0 or 1 in C
- Initialization of variables sized arrays in C
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



