Global Variable

That persnickey state that insists on showing up everywhere in your program. The common belief is that they should be avoided (GlobalVariablesAreBad).

The great thing about GlobalVariables is if you fix one, your whole program gets better! -- PhlIp (wink)

See also the SingletonPattern and the MonostatePattern, GlobalsInHeaders.

Why are global variables verboten? I doubt you can write a serious application without a single global variable, not counting the given data, code and stack segment pointers. -- SunirShah

How ironic. I came to this page to disagree. Our latest application doesn't have a single global variable, as that's a restriction of the platform. -- SunirShah

There must be some reason that two opposing views are signed by the same person. It's probably a really amusing one.

Hey, I agree big guy. I just wanted to get people debating about something other than religion and I figured that the "global variables" issue is always good for a debate. ;) -- RobertDiFalco

I have written a number of significant C applications without using a single global variable. However, all of them used the SingletonPattern (not that I realized it at the time). The problems with global variables are very similar to the problems with public fields in OO. Conceptually, if you consider variables form the current state logic of a StateMachine, global variables provide no defenses against InvalidStateTransition?s. For very simple cases, a careful programmer can avoid introducing an InvalidStateTransition? with the usual trend as the program becomes more complex.

In C, you protect yourself from InvalidStateTransition?s by making the global FileScope, and confine yourself to using functions to manipulate it. In JavaLanguage/SmallTalk, you can use the Singleton pattern.

Note that in this discussion I haven't mentioned the SoftwareMaintenance? hassles GlobalVariables introduce, the advantages during development are sufficient for me. This despite the fact that the maintenance issues tend to outweigh the development hassles over time. -- AndraeMuys

Like a goto, the global variable isn't always bad. The problem with some global variables is, it isn't obvious who has responsibility for changing the variable. see ProgramResponsibility.

See also GlobalVariablesAreBad, GlobalVariablesConsideredHarmful

EditText of this page (last edited November 20, 2013) or FindPage with title or text search