views:

2573

answers:

18

In C/C++, are global variables as bad as my professor thinks they are?

+8  A: 

Yes, but you don't incur the cost of global variables until you stop working in the code that uses global variables and start writing something else that uses the code that uses global variables. But the cost is still there.

In other words, it's a long term indirect cost and as such most people think it's not bad.

MSN
+4  A: 

Global variables are bad, if they allow you to manipulate aspects of a program that should be only modified locally. In OOP globals often conflict with the encapsulation-idea.

Leonidas
+11  A: 

My professor used to say something like: using global variables are okay if you use them correctly. I don't think I ever got good at using them correctly, so I rarely used them at all.

barneytron
So true. They are like gotos, if you don't know when to use them then never do.
David Holm
+10  A: 

Global variables are as bad as you make them, no less.

If you are creating a fully encapsulated program, you can use globals. It's a "sin" to use globals, but programming sins are laregly philosophical.

If you check out L.in.oleum, you will see a language whose variables are solely global. It's unscalable because libraries all have no choice but to use globals.

That said, if you have choices, and can ignore programmer philosophy, globals aren't all that bad.

Neither are Gotos, if you use them right.

The big "bad" problem is that, if you use them wrong, people scream, the mars lander crashes, and the world blows up....or something like that.

Downplaying the problems of using globals to a confused student is not a good idea IMO.
Geoffrey Chetwood
@Rich: That's a bunch of BS.
Anthony Cuozzo
Design Philosophy is not objective. Not in the least.Just because most programmers don't like something, doesn't mean one should never look into that something.It is easy to make general-use of globals without the world ending. Let him do it, struggle (knowing he would), and learn how.
Rich is right. This answer doesn't say anything about what is/isn't bad (or how globals can be used safely), only that "they're not as bad as all that. As such, it only downplays the problems.
jalf
+13  A: 

Yes.

jjnguy
And now the obligatory "No!!!", a la Even Stepvhen =)
Zach Scrivena
The question is yes or no, so that's how I feel compelled to answer.
jjnguy
Yeah, I know what you mean. Every time I see a Yes/No question, I imagine an Even Stepvhen debate.
Zach Scrivena
+8  A: 

I'd answer this question with another question: Do you use singeltons/ Are singeltons bad?

Because (almost all) singelton usage is a glorified global variable.

Gavin Miller
I was about to post a smart comment saying, "They're only bad if you call them globals instead of singletons", but you beat me to it.
smo
I'm still trying to figure out what the hell singletons are LOL.
GeoffreyF67
@Geoffrey: here are some good SO descriptions -- http://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch#11839 and for some good links: http://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch#65108
Gavin Miller
For the record, a singleton is a global variable with a glorified Design Patterns(tm)(lol) name to make it sound legitimate. It's equally bad for all the same reasons.
R..
+1  A: 

I think your professor is trying to stop a bad habit before it even starts.

Global variables have their place and like many people said knowing where and when to use them can be complicated. So I think rather than get into the nitty gritty of the why, how, when, and where of global variables your professor decided to just ban. Who knows, he might un-ban them in the future.

bong
+1  A: 

Global variables are generally bad, especially if other people are working on the same code and don't want to spend 20mins searching for all the places the variable is referenced. And adding threads that modify the variables brings in a whole new level of headaches.

Global constants in an anonymous namespace used in a single translation unit are fine and ubiquitous in professional apps and libraries. But if the data is mutable, and/or it has to be shared between multiple TUs, you may want to encapsulate it--if not for design's sake, then for the sake of anybody debugging or working with your code.

Michel
+34  A: 

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

Brian Rasmussen
This answer is really good. Combine this with the 'minimize variable scope' answer http://stackoverflow.com/questions/357187/global-variables-when-are-they-acceptable/357361#357361
bobobobo
+1  A: 

Global variables are fine in small programs, but horrible if used the same way in large ones.

This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.

When you are more experienced it will be easier to learn when they are okay.

Darron
+6  A: 

Global variables should only be used when you have no alternative. And yes, that includes Singletons. 90% of the time, global variables are introduced to save the cost of passing around a parameter. And then multithreading/unit testing/maintenance coding happens, and you have a problem.

So yes, in 90% of the situations global variables are bad. The exceptions are not likely to be seen by you in your college years. One exception I can think off the top of my head is dealing with inherently global objects such as interrupt tables. Things like DB connection seem to be global, but ain't.

Arkadiy
The one exception that *I* saw in my college years was graphics call-back functions. In XWindows, the mouse-callbacks didn't have void* data arguments that allowed you to pass around arbitrary chunks of program state... (not that that ends up being MUCH better than a global anyway...)
Brian Postow
+1 for "Things like DB connection *seem* to be global, but ain't."
R..
+4  A: 

As someone said (I'm paraphrasing) in another thread "Rules like this should not be broken, until you fully understand the consequences of doing so."

There are times when global variables are necessary, or at least very helpful (Working with system defined call-backs for example). On the other hand, they're also very dangerous for all of the reasons you've been told.

There are many aspects of programming that should probably be left to the experts. Sometimes you NEED a very sharp knife. But you don't get to use one until you're ready...

Brian Postow
A: 

Sooner or later you will need to change how that variable is set or what happens when it is accessed, or you just need to hunt down where it is changed.

It is practically always better to not have global variables. Just write the dam get and set methods, and be gland you when you need them a day, week or month later.

Bloodboiler
+3  A: 

Using global variables is kind of like sweeping dirt under a rug. It's a quick fix, and a lot easier in the short term than getting a dust-pan or vacuum to clean it up. However, if you ever end up moving the rug later, you're gonna have a big surprise mess underneath.

gnovice
A: 

No they are not bad at all. You need to look at the (machine) code produced by the compiler to make this determination, sometimes it is far far worse to use a local than a global. Also note that putting "static" on a local variable is basically making it a global (and creates other ugly problems that a real global would solve). "local globals" are particularly bad.

Globals give you clean control over your memory usage as well, something far more difficult to do with locals. These days that only matters in embedded environments where memory is quite limited. Something to know before you assume that embedded is the same as other environments and assume the programming rules are the same across the board.

It is good that you question the rules being taught, most of them are not for the reasons you are being told. The most important lesson though is not that this is a rule to carry with you forever, but this is a rule required to honor in order to pass this class and move forward. In life you will find that for company XYZ you will have other programming rules that you in the end will have to honor in order to keep getting a paycheck. In both situations you can argue the rule, but I think you will have far better luck at a job than at school. You are just another of many students, your seat will be replaced soon, the professors wont, at a job you are one of a small team of players that have to see this product to the end and in that environment the rules developed are for the benefit of the team members as well as the product and the company, so if everyone is like minded or if for the particular product there is good engineering reason to violate something you learned in college or some book on generic programming, then sell your idea to the team and write it down as a valid if not the preferred method. Everything is fair game in the real world.

If you follow all of the programming rules taught to you in school or books your programming career will be extremely limited. You can likely survive and have a fruitful career, but the breadth and width of the environments available to you will be extremely limited. If you know how and why the rule is there and can defend it, thats good, if you only reason is "because my teacher said so", well thats not so good.

Note that topics like this are often argued in the workplace and will continue to be, as compilers and processors (and languages) evolve so do these kinds of rules and without defending your position and possibly being taught a lesson by someone with another opinion you wont move forward.

In the mean time, then just do whatever the one that speaks the loudest or carries the biggest stick says (until such a time as you are the one that yells the loudest and carries the biggest stick).

dwelch
Is this just another way of saying "no one ever got fired for buying IBM"?
Gordon Potter
+3  A: 

Absolutely not. Misusing them though... that is bad.

Mindlessly removing them for the sake of is just that... mindless. Unless you know the advanatages and disadvantages, it is best to steer clear and do as you have been taught/learned, but there is nothing implicitly wrong with global variables. When you understand the pros and cons better make your own decision.

jheriko
+1  A: 

If it's possible your code will end up under intensive review during a Supreme Court trial, then you want to make sure to avoid global variables.

See this article: Buggy breathalyzer code reflects importance of source review

There were some problems with the style of the code that were identified by both studies. One of the stylistic issues that concerned the reviewers was the extensive use of unprotected global variables. This is considered poor form because it increases the risk that the program state will become inconsistent or that values will be inadvertently modified or overwritten. The researchers also expressed some concern about the fact that decimal precision is not maintained consistently throughout the code.

Man, I bet those developers are wishing they hadn't used global variables!

Casey
A: 

The important thing is to remember the overall goal: clarity

The "no global variables" rule is there because most of the time, global variables make the meaning of code less clear.

However, like many rules, people remember the rule, and not what the rule was intended to do.

I've seen programs that seem to double the size of the code by passing an enormous number of parameters around simply to avoid the evil of global variables. In the end, using globals would have made the program clearer to those reading it. By mindlessly adhering to the word of the rule, the original programmer had failed the intent of the rule.

So, yes, globals are often bad. But if you feel that in the end, the intent of the programmer is made clearer by the use of global variables, then go ahead. However, remember the drop in clarity that automatically ensues when you force someone to access a second piece of code (the globals) to understand how the first piece works.

Tom West