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 } |
- 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Initialization of global and static variables in C
- Difference between Static variables and Register variables in C
- Can we access global variable if there is a local variable with same name?
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- Redeclaration of global variable in C
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- How will you show memory representation of C variables?
- How are variables scoped in C - Static or Dynamic?
- What are the default values of static variables in C?
- Templates and Static variables in C++
- Operations on struct variables in C
- Initialization of static variables in C
- Initialization of variables sized arrays in C
- Variables and Keywords in C
- Static Variables in C
- C Program to print environment variables
- Scope of Variables in C++
- Constants vs Variables in C language
- Problem Solving on Storage Classes and Scoping of Variables
- Linking Files having same variables with different data types 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.

