10

I've been reading a lot about why global variables are bad and why they should not be used. And yet most of the commonly used programming languages support globals in some way.

So my question is what is the reason global variables are still needed, do they offer some unique and irreplaceable advantage that cannot be implemented alternatively? Are there any benefits to global addressing compared to user specified custom indirection to retrieve an object out of its local scope?

As far as I understand, in modern programming languages, global addressing comes with the same performance penalty as calculating every offset from a memory address, whether it is an offset from the beginning of the "global" user memory or an offset from a this or any other pointer. So in terms of performance, the user can fake globals in the narrow cases they are needed using common pointer indirection without losing performance to real global variables. So what else? Are global variables really needed?

3
  • From Here you will get some info. stackoverflow.com/questions/176118/…
    – Gangadhar
    Aug 31, 2013 at 11:46
  • @Gangadhar - there are no namespaces in C, but in C++ I can share visibility with a namespace, so how is that any different than using a global with visibility only limited to wherever it is needed?
    – user2341104
    Aug 31, 2013 at 11:48
  • @user2341104 as you said there are no namespaces in C. there is no possibility in C to declare or define global with visibility only limited to wherever it is needed(except declaring static Global variable to limit the scope of usage. ). and i was linked the above one which is having an answer with this line ** You have to ask Your self : Is that REALLY needed at a global scope** .this is the info which you get from there.
    – Gangadhar
    Aug 31, 2013 at 12:12

6 Answers 6

18

Global variables aren't generally bad because of their performance, they're bad because in significantly sized programs, they make it hard to encapsulate everything - there's information "leakage" which can often make it very difficult to figure out what's going on.

Basically the scope of your variables should be only what's required for your code to both work and be relatively easy to understand, and no more. Having global variables in a program which prints out the twelve-times tables is manageable, having them in a multi-million line accounting program is not so good.

0
6

I think this is another subject similar to goto - it's a "religious thing".

There is a lot of ways to "work around" globals, but if you are still accessing the same bit of memory in various places in the code you may have a problem.

Global variables are useful for some things, but should definitely be used "with care" (more so than goto, because the scope of misuse is greater).

There are two things that make global variables a problem: 1. It's hard to understand what is being done to the variable. 2. In a multithreaded environment, if a global is written from one thread and read by any other thread, you need synchronisation of some sort.

But there are times when globals are very useful. Having a config variable that holds all your configuration values that came from the config file of the application, for example. The alternative is to store it in some object that gets passed from one function to another, and it's just extra work that doesn't give any benefit. In particular if the config variables are read-only.

As a whole, however, I would suggest avoiding globals.

1
  • 1
    +1 for the "religious thing" & "some object passed from one function to another, extra work that doesn't give any benefit." - if globals solve a problem that otherwise requires passing a pseudo-global object, using the latter out of some misguided sense of purity is silly. My current project is based around a massive object that's the only 1 of its kind & wastes space/time firing this pointers everywhere. I tried making it a singleton...then realised it makes more sense to use (A) static variables if possible & globals wherever static scoping is prohibitive. It's all 1 program after all. Apr 8, 2016 at 11:37
5

Global variables imply global state. This makes it impossible to store overlapping state that is local to a given part or function in your program.

For example, let stay we store the credentials of a given user in global variables which are used throughout our program. It will now be a lot more difficult to upgrade our program to allow multiple users at the same time. Had we just passed a user's state as a parameter, to our functions, we would have had a lot less problems upgrading to multiple users.

1

my question is what is the reason global variables are still needed,

Sometimes you need to access the same data from a lot of different functions. This is when you need globals.

For instance, I am working on a piece of code right now, that looks like this:

static runtime_thread *t0;

void 
queue_thread (runtime_thread *newt)
{
   t0 = newt;
   do_something_else ();
}

void 
kill_and_replace_thread (runtime_thread *newt)
{
   t0->status = dead;
   t0 = newt;
   t0->status = runnable;
   do_something_else ();
}

Note: Take the above as some sort of mixed C and pseudocode, to give you an idea of where a global is actually useful.

2
  • But what if I simply declare them in the same namespace and use the namespace inside the functions?
    – user2341104
    Aug 31, 2013 at 11:45
  • @user2341104 You misunderstood my point. If you look at the example code I wrote for you, you need t0 to be globally accessible (in the same file, in this paricular case) by many functions that operate on it. You can not just define it into one function, because, if you do so, numerous others won't be able to access it. Aug 31, 2013 at 11:47
0

Static Global is almost mandatory when writing any cross platform library. These Global Variables are static so that they stay within the translation unit. There are few if any cross platform libraries that does not use static global variables because they have to hide their platform specific implementation to the user. These platform specific implementations are held in static global variables. Of course, if they use an opaque pointer and require the platform specific implementation to be held in such a structure, they could make a cross platform library without any static global. However, such an object needs to be passed to all functions within such a library. Therefore, you have a pass this opaque pointer everywhere, or make static global variables.

There's also the identifier limit issue. Compilers (especially older ones) have a limit to the number of identifiers they could handle within a scope. Many operating systems still use tons of #define instead of enumerations because their old compilers cannot handle the enumeration constants that bloat their identifiers. A proper rewrite of the header files could solve some of these.

-1

Global variables are considered when you want to use them in every function including main. Also remember that if you initialize a variable globally, its initial value will be same in every function, however you can reinitialize it inside a function to use a different value for that variable in that function. In this way you don't have to declare the same variable again and again in each function. But yes they can cause trouble at times.

  • List item

Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local

  • And if you make a mistake while declaring a global variable, then you'll have to apply the changes to the whole program like if you accidentally declared it to be int instead of float
1
  • "if you initialize a variable globally, its initial value will be same in every function, however you can reinitialize it…to use a different value for that variable in that function" …what? No. Either you are changing the global variable for all future functions to see (i.e. not "initial value will be same"), or you're declaring a different local that just happens to have the same name, hiding the global and being unable to leave the function's scope. In either case, it's likely that you're gonna have a bad time. Apr 8, 2016 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.