Why to avoid global variables

Hi,

I recently finished a c++ class and the instructor mentioned this so many times, he insisted that we should try to avoid global variables because they could cause problems but I never asked the alternative to achieve the same result, I know I could add local variables but what about DRY? do not repeat your self.

In fact I actually like adding global variables because I think it makes everything easy.

Can someone be so kind and briefly explain the possible problems global variables may cause?

Also what would be the alternative for global variables?

Thanks a lot.

closed account (o1vk4iN6)
They can be accessed and modified anywhere. So if you have hundreds of thousands of lines of code, it can be difficult to debug. Although that doesn't mean it shouldn't be used, ie cout, cin.
Last edited on
n fact I actually like adding global variables because I think it makes everything easy.

It's easier to do like it's easier to put your dirty laundry in a pile under your bed. But then when you want to find a pair of close to wear, you have to sift through it all, and check if it's clean.

Can someone be so kind and briefly explain the possible problems global variables may cause?

Lets say that you want to make a change to part of a program that depends on a global variable. How do you know what changes will occur in the rest of the program if you modify it? You have to find everywhere it's used, figure out which order it might get used in, etc.

But the real danger comes when you rely on that global variable for something, and someone ( you or another person) , adds code to change that variable in some obscure place. Now you have a disaster waiting to happen.

It's best to localize as much as possible, so that everything your working with is contained as much as possible. That way it's much more difficult to introduce bugs, and it's much easier to trace where they come from.

Also what would be the alternative for global variables?

Communication. Everything should be on a need to know basis.
Last edited on
Another reason globals are bad is they make your code rigid and less flexible.

Copy/paste from a previous post of mine:

global variables are ATROCIOUS and you should really avoid using them. They severely cripple your code and make program management and maintenance much more difficult. They may seem simpler for small program, but as your program gets larger, they will make things more and more unwieldly.


They also get you in the practice of writing crappy code that is not reusable. When your code works with a global... it ONLY works with that global. When your code works with parameters, it can work with ANYTHING, making it much more functional and much more reusable.


Here's a classic example. Let's say you're writing a simple game and have a player fighting a goblin. You decide to have player and goblin life/hp stored as global variables.

Then you write a function to damage the player:

1
2
3
4
5
6
7
8
9
int playerhp = 100;
int goblinhp = 20;

// hurts the player, returns true if the player is still alive, false if the player is dead
bool HurtPlayer( int damage )
{
  playerhp -= damage;
  return (playerhp > 0);
}



Seems fine, right?

The problem is... that function only works with the player. Say you want to do the same thing with the goblin. You now have to write an entirely separate function:

1
2
3
4
5
6
// likely just a copy/paste of HurtPlayer
bool HurtGoblin( int damage )
{
  goblinhp -= damage;
  return (goblinhp > 0);
}



Now what happens when you want to add more enemies? Or more players? Do you copy/paste this function for all of them? What if you want to change how these functions work (to add some kind of defense calculation or something). Do you go back and change each and every one of the dozen identical functions?


Because you used globals, the functions can only be used with those globals. It makes them extremely restrictive.


Compare that to a function that uses no globals:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool DamageObject( int& objecthp, int damage )
{
  objecthp -= damage;
  return (objecthp > 0);
}

//...

int main()
{
  // to damage the goblin
  DamageObject( goblinhp, 5 );

  // to damage the player
  DamageObject( playerhp, 4 );

  // etc  






And that's just one example of why globals are horrible. There are many more.
Hey fstigre....

iseeplusplus Said it right.....

The alternative for global variables could be static variable and static functions , with making them more protective to use.
static variables/functions kind of are globals... just in a smaller namespace.

The real alternative to globals is passing appropriate information to code that needs it (often times this means function parameters).
Thank you all for the good advice, I see the point I just need to think more about using other alternatives such as function parameters or static variables.

Thank you all very much.

They can be accessed and modified anywhere. So if you have hundreds of thousands of lines of code, it can be difficult to debug. Although that doesn't mean it shouldn't be used, ie cout, cin


I'd argue this applies to cout and cin as well.

Recently I've been debugging a *very* big program that somewhere in the middle of operation printed just a single word "f*ck" to the stdout. Where the f*ck it came from?! Instead of using cout, you should be using a proper logging library which encapsulates calls to cout, so you can easly track who is outputting and what, and eventually filter your logs.
closed account (o1vk4iN6)
Yes the implementation of cout and cin is meant to be as basic as possible. If the implementations always outputted the line of code and function from which it was from, it would have undesired fluff (it's your job to make it useful). If all you chose to output was "f*ck", I'd suggest a more descriptive message. The logging library which encapsulates cout, as you say, still needs to access cout. Which would still require it to be a global variable. I do not see what you are trying to argue.
Last edited on
I do not see what you are trying to argue.
The point is you shouldn't use any globals, even the standard ones. It's not entirely possible, possibly the only things that should be accessible in this way are really fundamental factory/creator methods; just enough to get started.

In principle, every object should have as local a scope as possible
Last edited on
Topic archived. No new replies allowed.