When is it ok to use a global variable in C?

Adam Davis picture Adam Davis · Oct 6, 2008 · Viewed 41.3k times · Source

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.

-Adam

Answer

Dan Cristoloveanu picture Dan Cristoloveanu · Oct 6, 2008

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?