Why Global Vars in C Are Bad

I know, this is in some way a rather religious topic, but I was interested in how to properly code C and in how to handle variables and variable-passing to functions in a clean way. After doing some research I come to the following conlcusion.

When Writing Non-Multi-Threaded Programs

Below are my personal recommendations when writing single-threaded programs (e.g. no pthreads library involved at all).

  • Variables should always remain in the smallest scope possible. Every time you increase the scope, there is potentially more code which can modify your variable in an probably unintended way.
  • Larger variable scopes increase complexity, especially when debugging code, since the error could be located on every line in your code.

So in terms of keeping complexity as low as possible, try to avoid global variables in your code if possible and if the design allows it.

When Writing Multi-Threaded Programs

Some basic recommendations when writing multi-threaded programs. In multi-threaded programs, threads will share all global variables and file descriptors with the parent process (see [2]). Therefore, they’re sometimes called “lightweight processes”. One important thing to know is, that local variables are not shared between threads – they’re local to each thread. If several threads run concurrently, there must be some protection measure in order to control access to global variables and stuff like that. Here’s the main recommendation:

  • Use mutexes to protect prevent race conditions (see [3]) and protect access to your global variables.

Sorry, for this article beeing a bit short. I am going to extend this article, as soon as I have other findings. Anyway, comments are always welcome 🙂


[1] http://stackoverflow.com/questions/176118/when-is-it-ok-to-use-a-global-variable-in-c
[2] http://www.linuxjournal.com/article/3138
[3] https://en.wikipedia.org/wiki/Race_condition

Leave a Reply

Your email address will not be published. Required fields are marked *