Bad to have global variables?

closed account (jwkNwA7f)
I have heard that it is bad to have global variables, why?

Thank you!
This question has been asked numerous times and you can easily find an answer by using Google:
https://www.google.ca/#q=why+are+global+variables+bad

And the first few results:
http://c2.com/cgi/wiki?GlobalVariablesAreBad
http://stackoverflow.com/a/485020
closed account (jwkNwA7f)
@Danny Thank you! That is kinda what I had thought, but I had wanted to hear what some others thought
I think
global variables are bad
is a wrong expression ,I prefere global variables could be bad in same cases also useful in others

global variables are helpful when a various functions share the same data,or when a variable holds value through the program's lifetime

but there some side effect when using variable
1 : It take up a memory the entire time of program's excution
2 : When working with large programs ,using large numbers can leads to program errors due to miss-modification to it
3 : sometimes a local variables cannot shares the same name with a global one for exp

1
2
3
4
5
6
7
8
9
10
11
12
# include <iostream>

int globalVar = 9;

int main()
{
    int globalVar = 99;

    std::cout << globalVar << std::endl;

    return 0;
}


One important point, if we examin this exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# include <iostream>
using namespace std;

int firstNbr = 0;

int main()
{
    int secondNbr = 0;
    {
        int thirdNbr = 0;
    }
    
    return 0;
}


I think the most probably think that firstNbr is a the only global variable where in fact secondNbr is global variable too
every variable that precede a scope is a global variable to this scope

hope that helps ,also hope getting some critics
also hope getting some critics

A'ight, I'll play devil's advocate ;)

I prefere global variables could be bad in same cases also useful in others

We could say the same thing about goto, no? Using proper program design, we are generally able to circumvent these cases.

global variables are helpful when a various functions share the same data

Functions take arguments, we could just pass the shared data as an argument to those functions. Again, with proper program design, we can avoid these cases.

when a variable holds value through the program's lifetime

Static. Variables. http://images.wikia.com/adventuretimewithfinnandjake/images/b/b3/Kevin-Butler-Mind-Blown.gif

in fact secondNbr is global variable too

No, secondNbr is LOCAL to the main method, it is not in the global scope. Try adding a function after main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# include <iostream>
using namespace std;

int firstNbr = 0;

int main()
{
    int secondNbr = 0;
    {
        int thirdNbr = 0;
    }
    
    return 0;
}

void foo()
{
    std::cout<< "The second number is: "<< secondNbr<< '\n';
}
error: 'secondNbr' was not declared in this scope


If secondNbr was in the global scope, foo would have access to it... which it doesn't.

every variable that precede a scope is a global variable to this scope

Now you're just splitting hairs.
Last edited on
Global variables are outside of all scopes besides the global scope, or the scope of the translation unit.
Local variables are within a scope that is within the global scope, so I would agree with Danny Toledo in this case.

Your example, Techno, is of a local variable in one function's scope with another local variable that is in a more restrictive scope. You could say the second is more localized.

Any variable within the scope of a function only holds a lifetime for as long as the function is running or the control remains in the scope. As soon as the control leaves the scope, all local variables in that scope are destroyed.


@OP
Do not get into the mindset where there is an absolute wrong and an absolute right.
For the most part, you will find better alternatives to global variables. That is not to say there is absolutely no place for them in a program. You can look at two common global variables: std::cout and std::cin.
One use for a global variable is perhaps a singleton instance of a logging class. It makes sense to only have one Log object present and to be able to modify it anywhere in the program (just for logging information of course).
I say if you have a variable/object whose purpose is to be modifiable anywhere and at any scope AND it only makes sense to have just one instance of it, you can justify the need for a global variable.

However, make sure you explore possible alternatives first before resorting to global variables. They can bring ruin to your program if not handled properly.
Last edited on
You can look at two common global variables: std::cout and std::cin

By your own definition1, you are wrong with this statement. All components of the standard namespace are in the scope of namespace std.

1
Global variables are outside of all scopes besides the global scope
Ah right, I forgot about that. Thanks for correcting me.
@Danny Toledo
We could say the same thing about goto, no?
I agree with this

Functions take arguments, we could just pass the shared data as an argument to those functions. Again, with proper program design, we can avoid these cases.

Yes thats a way but not efficient as the case with global variable

One important point, if we examin this exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# include <iostream>
using namespace std;

int firstNbr = 0;

int main()
{
    int secondNbr = 0;
    {
        int thirdNbr = 0;
    }
    
    return 0;
}


I think the most probably think that firstNbr is a the only global variable where in fact secondNbr is global variable too
every variable that precede a scope is a global variable to this scope


garbage ,I checked a global variable is the one when It precede all functions

http://images.wikia.com/adventuretimewithfinnandjake/images/b/b3/Kevin-Butler-Mind-Blown.gif
so rude ,and be curful,you may not see that you're insulting some well-known cpp writers like the one who writes

Global variables are helpful when the same data is used by several
functions in your program, or when a variable must hold its value throughout the duration of the program.
C++ from the Ground Up ~ 3rd Edition (McGraw~2003.03)(Herbert Schildt)

Last edited on
so rude

It was meant sarcastically, however I do see how it may be taken the wrong way. My Apologies.

you may not see that you're insulting some well-known cpp writers

Just Googled this Herbert Schildt guy:

http://www.cplusplus.com/forum/lounge/75040/#msg402940
http://www.seebs.net/c/c_tcn4e.html
http://catb.org/esr/jargon/html/B/bullschildt.html
Synonym for well-known: notorious.

Globals and goto are dark side: apparently swift and easy. Powerful too. They can lead to suffering.
closed account (zb0S216C)
http://www.cplusplus.com/forum/general/88920/#msg477397

Wazzak
It might be helpful if some of the more experienced members chime in1. I've done some Google searches, and there seem to be some areas where the "side effects" (ex. lack of consistency) of globals are beneficial (and the users here seem to have quite diverse backgrounds and are possibly able to provide their own examples).

A user named "Jamie" explains his/ her use of global random number generators in the comment section of the following link, and the post before that mentions threads (of which I have close to no understanding):
http://www.learncpp.com/cpp-tutorial/42-global-variables/

Synonym for well-known: notorious.

I have admittedly never read any of his books, but they (his books) seem to be quite popular among the beginner/ intermediate ranks. That being said, I can't be quick to judge him, as, wherever possible, I prefer to judge by my own knowledge and not by the words of others.

I do concede that there may be instances where shared data is better as a global variables.

That is, however, as far as I think I will take my end of this discussion. As I said in my first post, this question has been asked (and answered) many times. With that, I leave more links:

http://www.cplusplus.com/forum/general/76476/
http://www.cplusplus.com/forum/beginner/100335/
http://www.cplusplus.com/forum/beginner/22956/
http://www.cplusplus.com/forum/beginner/6958/

1You can find many of their answers to this question in some of the links provided. If you do some extra searching, you're likely to find more.

PS.
With regards to members of a namespace, according to the working draft of the C++ standard:
ISO N3960 ยง 3.3.2.[1]-
Every name is introduced in some portion of program text called a declarative region, which is the largest part
of the program in which that name is valid
, that is, in which that name may be used as an unqualified name
to refer to the same entity. In general, each particular name is valid only within some possibly discontiguous
portion of program text called its scope. To determine the scope of a declaration, it is sometimes convenient
to refer to the potential scope of a declaration. The scope of a declaration is the same as its potential scope
unless the potential scope contains another declaration of the same name. In that case, the potential scope
of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration
in the outer (containing) declarative region.


So I guess components of the standard namespace are indeed global. That means I... I... I was wrong. :(
Last edited on
> I have heard that it is bad to have global variables, why?

Global variables are not bad per se - it is unnecessary programmatic visibility that is ideally avoided. Incidentally, I'm quite relieved that you didn't state that "global variables are evil".

For example, in a component, we need a variable (say an int common) - an implementation detail - that is required to be shared across several (non-inline) functions in our implementation:

1
2
// in the header
extern int common ; // common is visible in the entire program, it pollutes the global namespace 


1
2
3
4
5
6
// in the header
namespace my_impl
{
    extern int common ; // better; though my_impl::common is visible in the entire program, 
    // at least it does not pollute the global namespace
}


1
2
3
4
5
6
7
8
9
10
// in the header
class A   
{
     // ....
    
    private:
       static int common ; // even better
       // though A::common is visible in the entire program, 
       // access to it is restricted to members and friends of A 
};



1
2
3
// in the implementation file, at file scope
static int common ; // best, common with internal linkage
    // is not programmatically visible outside our implementation 


1
2
3
4
5
6
// or, in the implementation file
namespace
{
    int common ; // also best, common in an anonymous namespace 
    // is not programmatically visible outside our implementation
}
Topic archived. No new replies allowed.