Karl said:
Global variables are almost always, and I really believe what I write
here, *almost always*, a source of a problem. You can eliminate them
easily by passing things around, at least that's what function arguments
are for and why they were invented.
I gotta tell you that blanket statements can do much more harm than good.
I wish that we all could get into the habit of justifying statements w/
authoritive sources or real-world experiences.
If you don't have sources to attribute to, say that 'in my opinion' or
'personal experience has shown' and then go off and explain why you feel that
way.
---
In my experience, globals can be the source of problems, bugs, race conditions,
etc. when implemented and used improperly or in a non-standard way without
supporting documentation and pre-meditated design. One of the biggest problems
that I've seen is when globals are used to hold read/write data -- it comes
down to what can/should write to the global, and how are potential readers
notified by the change? A global that changes value a lot, or is nothing more
than a lazy way to get out of passing parameters should definitely be a cause
for concern and a thorough code review.
I've seen and used cases where a global (read-only) variable makes perfect
sense, and is appropriate. For instance, some operating systems have a notion
of a process or instance identifier that is unique for that process. That
identifier is passed into main on program startup, but is otherwise
unavailable. Storing the value of the process id in a global variable can be
justified, but I'd stress that you attempt to guard it from modification by
making access to it read-only. In this case, problems can arise if you
inadvertantly write to it, which can be much easier than it seems if you are
using equality such as if (global_instance = 123) when if (global_instance ==
123) was intended. I'm sure that Karl was speaking of this type of bug which
can be difficult at best to narrow down.
There are numerous authorative resources out there on the subject of globals.
Research and understand the ramifications of global now while you are still
learning as it can be much harder to change bad habits down the road.