Why are global variables bad, in a single threaded, non-os, embedded application

loneRanger picture loneRanger · May 16, 2009 · Viewed 18.8k times · Source

Most of the objections I see to using global variables make sense since they refer to issues of multiple threads, thread safety, etc.

But in a small, single threaded, non-OS, case, what objections do you have? In my case, I'm writing my embedded system in "C", if it matters. I'm also the only developer on the product.

Why would eliminating global variables make my code better?

(After reading several responses, I realize I also should have pointed out that this system has no dynamic memory allocation (e.g. malloc). All the memory is statically allocated at compile time.)

Answer

Will Hartung picture Will Hartung · May 16, 2009

It wouldn't.

The two fundamental issues with global variables is simply cluttering the namespace, and the fact that "no one" has "control" over them (thus the potential collisions and conflict with multiple threads).

The "globals are bad", like pretty much every other computer programming idiom is a guideline, not a hard and fast rule. When these kinds of "rules" are made, its best rather than simply adopting the rule by rote to understand the circumstances and motivations behind the creation of the rule. Don't just take them blindly.

In your case, you seem to understand the nature of your system and the arguments around the rule and decided that it doesn't apply in this case. You're right, it doesn't.

So, don't worry about it.