On these forums, most of the people have been told that globals are evil. |
To be fair, I wasn't really told this, I just discovered it for myself. ;P Or if I was told, it didn't sink in until I saw for myself.
Anyway here's my 2 cents:
Globals are a quick-n-dirty way to get something done. They admittedly make it easier to slap something together in a rush, but they have numerous other problems that beginners tend to not notice. These problems become more and more apparent the larger a project becomes, or the more time that passes between project updates.
Constants are no exception. They suffer from all the same ails that global variables do.
The biggest problem with globals is that they destroy expandability / code reusability (Albatross mentioned this somewhat... "if you're trying to make modular code"). Basically... code you write that uses globals
will only work with those globals. That is, they'll only work with that single data set.
Let's take this classic example. Say you're making a game and you want to have a routine that heals the player:
1 2 3 4 5 6 7 8
|
// playerlife, playermaxlife are both global
void HealPlayer(int heal)
{
playerlife += heal;
if(playerlife > playermaxlife)
playerlife = playermaxlife;
}
|
Seems harmless... but what if you decide later that you want multiple players? Do you have to write a seperate routine for each one?
What if you want to recycle this routine so it can heal enemies as well? Do you create a seperate HealEnemy function that is just a copy/paste but uses different variables?
Globals make any code that uses them inflexible. The code cannot be applied to similar tasks where it probably should be able to.