Global Variables

My friend has recently responded to a member of another forum with this: The reason you use global variables is to allow the use of the variable throughout the file or when the file is included by another. If it was 'bad' it wouldn't be part of C++ and would raise a compilation error.

Does this justify the use of global variables?
no that is not a good reason to use global variables that't like saying because goto and system are there you should use them.
You should always use local variables unless the same variable is being used in several different functions eg a static variable
http://www.cplusplus.com/doc/tutorial/variables/
Scope of variables
All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.

A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block.


Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration.

The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.
Last edited on
You can dereference uninitializated or null pointer ergo dereferencing such pointes are not bad.
You can make all class members public, ergo it is not bad.
when the file is included by another
It will lead to compilation error actually.

http://c2.com/cgi/wiki?GlobalVariablesAreBad
http://stackoverflow.com/questions/484635/are-global-variables-bad
Global objects can and will sometimes mess up your program especially if one of them needs to be initialized before other.

Rule of thumb: if you cannot understand why global variables bad, you shouldn't use them. In other case you have enough experience to decide if there is need for them.

There is OOP compliant alternative: singleton pattern.
Last edited on
Topic archived. No new replies allowed.