pros and cons of Global Variables and Local Variables?

Started by
3 comments, last by dashurc 14 years, 7 months ago
For C++. Anyone know? I'm a bit newbish so I'm not 100% sure. If you need anymore info let me know
Advertisement
pro: sharing is easy

con: anyone can change a global variable, so if something goes wrong with it, the bug could be anywhere in your code
Quote:Original post by DevFred
con: anyone can change a global variable, so if something goes wrong with it, the bug could be anywhere in your code

And in any thread. Or threads.
I typically stick all my variables inside a class and make them private so that only the class can change them. That way it is very easy to group and categorize the code in a logical manner.

If I create a global I'll usually make is constant so that no one can change it.
Personally I prefer to never use global variables for the same reason that proper encapsulation of classes is so important.

Global variables make your code very hard to maintain and aren't necessary in even a mediocrely designed system.

Local variables on the other hand are used as required (within the scope of whatever function in which they are defined). Are you confusing them with member variables?

This topic is closed to new replies.

Advertisement