- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why should we avoid using global variables in C/C++?
We should avoid using global variables in any language, not only C++. This is because these variables pollute the global namespace, can cause some very nasty bugs in big projects as they can be accessed from any file and hence be modified from anywhere. These are some of the reasons why global variables are considered bad −
Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use.
A global variable can have no access control. It can not be limited to some parts of the program.
Using global variables causes very tight coupling of code.
Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value.
Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
Note that sometimes you just have to use a global variable. But before doing so make sure if you have any alternative. Read more about global variables in the c2 wiki − http://wiki.c2.com/?GlobalVariablesAreBad
- Related Articles
- Why we should avoid using std::endl in C++
- Why we do not have global variables in C#?
- How and why to avoid global variables in JavaScript?
- Why are global variables bad in C/C++?
- Why should we avoid wastage of food ?
- Why we should avoid eating fast food?
- Global and Local Variables in C#
- What are global variables in C++?
- Why are global and static variables initialized to their default values in C/C++?
- What are local variables and global variables in C++?
- Initialization of global and static variables in C
- Global variables in Java
- How are C++ Local and Global variables initialized by default?
- Global Scope Variables in Postman?
- Global Variables in Lua Programming
