Why is global variables bad?

Why does people say it is bad practice and should be avoided if possible? Is it security reasons? Harder to crack etc?

Is it better to create a class and combine variables for functions inside that class?
One reason is that when a function is done with x and y it doesn't have to remember their values anymore so the program runs more efficiently, quickly and takes fewer resources. Of course making x and y global variables and using the same ones over and over with different values would probably be marginally better.

Think of it this way, if you make a video game do you want the game to have to store in memory all the game's data at once? Or just what it needs for this level?

I'm sure there are other reasons too but I am a newb.
Last edited on
closed account (zb0S216C)
Minimacfox wrote:
"Why does people say it is bad practice and should be avoided if possible?"

http://www.cplusplus.com/forum/general/88920/#msg477397 In addition to what I wrote in the link, global variables reside in a completely different place within a program's memory map; automatic storage reside on the stack, global storage resides within a special area of memory specifically for read-only/static data, and dynamically allocated storage resides on heap. Also, global storage is accessible to all translation units, further increasing the likelihood of ambiguities.

Minimacfox wrote:
"Is it security reasons? Harder to crack etc?"

Possibly; it depends on what type of data you place in the global-namespace. Crackers could potentially use their knowledge of global storage the harvest information from the executable.

Last edited on
Topic archived. No new replies allowed.