- 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 are global variables bad in C/C++?
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
#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
- Related Articles
- What are global variables in C++?
- Why should we avoid using global variables in C/C++?
- What are local variables and global variables in C++?
- Why are global and static variables initialized to their default values in C/C++?
- Why we do not have global variables in C#?
- Global and Local Variables in C#
- How are C++ Local and Global variables initialized by default?
- Initialization of global and static variables in C
- How and why to avoid global variables in JavaScript?
- Global variables in Java
- Why are "continue" statements bad in JavaScript?
- Global Scope Variables in Postman?
- Global Variables in Lua Programming
- Why “using namespace std” is considered bad practice in C++
- Why are women considered bad drivers?
