Question about global variables

I always see people advising against the use of global variables; since I'm a beginner, I haven't experienced the downfalls yet.

Is it common to use global constant string arrays to be referenced throughout different functions? What are the downsides of using global constants?
Last edited on
• Any function can modify them. Rules imposed on a global variable can be easily forgotten.

• Threading. They are not thread-safe. Since any function can access them, synchronization becomes problematic, especially when multiple translation units attempt to modify it.

• Dependency. A part of a program may depend on its use, and modification or removal of the variable could cause compilation of the program to fail.

Aceix.
Thank you for your reply.

All of the issues seem to be focused around the modifying of them from a global state.

Would these problems persist if they were constants?
Would there be any other downsides when using global constants?
Would these problems persist if they were constants?

No.

Would there be any other downsides when using global constants?

Not when it is necessary.

Aceix.
Ah okay :) Thank you.
The only problem you could get with global constants is flooding the global namespace. The names you pick for the global constants could conflict with other variables elsewhere in your code, and if it's spelt similarly to another variable you could mistake one for the other introducing a subtle bug. Naming conventions (like capitalising all global constants or prefixing them with "g_" ) and enclosing constants in a namespace can help against this.
Ah I see. Than you for the tip Lachlan Easton. I will keep naming conventions in mind.
Topic archived. No new replies allowed.