Re: Can I avoid using a global?!
mike3 <mike4ty4@yahoo.com> wrote:
I've got this problem. I was building a game in C++, and ran into
this, which is causing me some trouble. I was wondering if I could
avoid using a global here since I've heard that globals are "bad".
I've also heard global _functions_ are bad too. If that's the case,
then this seems impossible to do without using one: how can we draw to
the screen, which seems to require a set of screen drawing functions
that you can call from anywhere, or a "singleton" screen object (bad
too!), etc. etc. etc.?
You can avoid some (although not all) problems with globals by putting
them inside appropriately-named namespaces.
On situation where I sometimes do this is when I need some compile-time
constants that affect completely separate and independent parts of the
program. When I put such constants in header files, these files double as
very efficient configuration files for the program (which is especially
useful if you are in a project with multiple developers, not all of them
programmers; for example if a level designer or graphics artist would want
to tweak some setting in the program, he can simply open the approperiate
"configuration file", change the values as needed, and hit the build button.)
Such a file would typically look like:
namespace Settings
{
// The width and height of the grid
const int kGridWidth = 15, kGridHeight = 15;
...
}
(Sometimes even if such a constant affects only *one* single part of
the program, perhaps even one single *line*, I put it in such a header
file because, as said, it doubles as a "configuration" file where all
the compile-time settings are grouped for easy tweaking.)