views:

2607

answers:

12

Apparently there's a lot of variety in opinions out there, ranging from, "Never! Always encapsulate (even if it's with a mere macro!)" to "It's no big deal - use them when it's more convenient than not."

So.

Specific, concrete reasons (preferably with an example)

  • Why global variables are dangerous
  • When global variables should be used in place of alternatives
  • What alternatives exist for those that are tempted to use global variables inappropriately

While this is subjective, I will pick one answer (that to me best represents the love/hate relationship every developer should have with globals) and the community will vote theirs to just below.

I believe it's important for newbies to have this sort of reference, but please don't clutter it up if another answer exists that's substantially similar to yours - add a comment or edit someone else's answer.

+3  A: 

Global variables in C are useful to make code more readable if a variable is required by multiple methods (rather than passing the variable into each method). However, they are dangerous because all locations have the ability to modify that variable, making it potentially difficult to track down bugs. If you must use a global variable, always ensure it is only modified directly by one method and have all other callers use that method. This will make it much easier to debug issues relating to changes in that variable.

Jeff Yates
A: 

I'm in the "never" camp here; if you need a global variable, at least use a singleton pattern. That way, you reap the benefits of lazy instantiation, and you don't clutter up the global namespace.

Nik Reiman
While I don't disagree, keep in mind that the focus here is C - there are no classes. Can you show how to implement a singleton in C? One of the major advantages OO programming has over C is this sort of design pattern...
Adam Davis
Singletons are not the answer to global variables, they only allow programmers to change the style of the declaration while being lazy (in a bad way) with lifetime management. Singletons cause me more problems than global variables.
Torlack
+1  A: 

It's a tool like any other usually overused but I don't think they are evil.

For example I have a program that really acts like an online database. The data is stored in memory but other programs can manipulate it. There are internal routines that act much like stored procedures and triggers in a database.

This program has a hundreds of global variables but if you think about it what is a database but a huge number of global variables.

This program has been in use for about ten years now through many versions and it's never been a problem and I'd do it again in a minute.

I will admit that in this case the global vars are objects that have methods used for changing the object's state. So tracking down who changed the object while debugging isn't a problem since I can always set a break point on the routine that changes the object's state. Or even simpler I just turn on the built in logging that logs the changes.

Kevin Gale
+2  A: 

You need to consider in what context the global variable will be used as well. In the future will you want this code to duplicate.

For example if you are using a socket within the system to access a resource. In the future will you want to access more than one of these resources, if the answer is yes I would stay away from globals in the first place so a major refactor will not be required.

JProgrammer
+1  A: 

I came from the "never" camp, until I started working in the defense industry. There are some industry standards that require software to use global variables instead of dynamic (malloc in the C case) memory. I'm having to rethink my approach to dynamic memory allocation for some of the projects that I work on. If you can protect "global" memory with the appropriate semaphores, threads, etc. then this can be an acceptable approach to your memory management.

gthuffman
Interesting. The defense industry put me firmly in the "never" camp.
Ben Collins
I worked on an embedded system where dynamic memory allocation wasn't available. In that case we needed 'global' variables allocated in RAM-space (for image data) by the linker and had to control access between multiple threads.It is a different school of thought, but it can work.
Adam Hawes
+10  A: 

Variables should always have the smaller scope possible. The argument behind that is that every time you increase the scope you have more code that potentially modifies the variable, thus more complexity is induced in the solution.

It is thus clear that avoiding using global variables is preferred if the design and implementation naturally allows that. Due to this I prefer not using global variables unless they are really needed.

I can not agree with the "never" statement either, Like any other concept global variables are a tool that should be used when needed. I would rather use global variables than use some artificial constructs (like passing pointers around) which would only mask the real intent. Good examples where global variables are used are singleton pattern implementations or register access in embedded systems.

On how to actually detect excessive usages of global variables: inspection, inspection, inspection. Whenever I see a global variable I have to ask myself: Is that REALLY needed at a global scope?

Dan Cristoloveanu
+1  A: 

Global variables should be used when multiple functions need to access the data or write to an object. For example, if you had to pass data or a reference to multiple functions such as a single log file, a connection pool, or a hardware reference that needs to be accessed across the application. This prevents very long function declarations and large allocations of duplicated data.

You should typically not use global variables unless absolutely necessary because global variables are only cleaned up when explicitly told to do so or your program ends. If you are running a multi-threaded application, multiple functions can write to the variable at the same time. If you have a bug, tracking that bug down can be more difficult because you don't know which function is changing the variable. You also run into the problem of naming conflicts unless you use a naming convention that explicitly gives global variables a unique name.

Steropes
A: 

When you declare constants.

+2  A: 

When you're not worried about thread-safe code: use them wherever it makes sense, in other words wherever it makes sense to express something as a global state.

When your code may be multi-threaded: avoid at all costs. Abstract global variables into work queues or some other thread-safe structure, or if absolutely necessary wrap them in locks, keeping in mind that these are likely bottlenecks in the program.

Dan
+4  A: 

Consider this koan: "if the scope is narrow enough, everything is global".

It is still very possible in this age to need to write a very quick utility program to do a one-time job.

In such cases, the energy required to create safe access to variables is greater than the energy saved by debugging problems in such a small utility.

This is the only case I can think of offhand where global variables are wise, and it is relatively rare. Useful, novel programs so small they can be held completely within the brain's short-term memory are increasingly infrequent, but they still exist.

In fact, I could boldly claim that if the program is not this small, then global variables should be illegal.

  • If the variable will never change, then it is a constant, not a variable.
  • If the variable requires universal access, then two subroutines should exist for getting and setting it, and they should be synchronized.
  • If the program starts small, and might be larger later, then code as if the program is large today, and abolish global variables. Not all programs will grow! (Although of course, that assumes the programmer is willing to throw away code at times.)
Paul Brinkley
+4  A: 

The only way you can make global variables work is to give them names that assure they're unique.

That name usually has a prefix associated some some "module" or collection of functions for which the global variable is particularly focused or meaningful.

This means that the variable "belongs" to those functions -- it's part of them. Indeed, the global can usually be "wrapped" with a little function that goes along with the other functions -- in the same .h file same name prefix.

Bonus.

When you do that, suddenly, it isn't really global any more. It's now part of some module of related functions.

This can always be done. With a little thinking every formerly global variable can be assigned to some collection of functions, allocated to a specific .h file, and isolated with functions that allow you to change the variable without breaking anything.

Rather than say "never use global variables", you can say "assign the global variable's responsibilities to some module where it makes the most sense."

S.Lott
+1 - Bravo. These are the types of things people did in the old days before we knew that global variables are so "evil". Shockingly, those old programs still worked and often were still maintainable. :)
Torlack
A: 

Global constants are useful - you get more type safety than pre-processor macros and it's still just as easy to change the value if you decide you need to.

Global variables have some uses, for example if the operation of many parts of a program depend on a particular state in the state machine. As long as you limit the number of places that can MODIFY the variable tracking down bugs involving it isn't too bad.

Global variables become dangerous almost as soon as you create more than one thread. In that case you really should limit the scope to (at most) a file global (by declaring it static) variable and getter/setter methods that protect it from multiple access where that could be dangerous.

Adam Hawes