Global Variables

Jan 14, 2009 at 7:25pm
Hi,

I was wondering, what are the disadvantages of using global variables? How does c++ keep track of them, etc.

Also, is there any chance that global variables can change without something acting on them?

Is it best practice to avoid globals?
Jan 14, 2009 at 7:50pm
The disadvantages is that you cannot re-use the same variable name anywhere, so if you have a global named "position", you cannot use "position" anywhere else even if it would make sense. Yes, it is good practice to avoid globals, generally having a lot of globals means you are not implementing OO correctly.
Jan 14, 2009 at 8:53pm
If you declare a global it is possible to have a local with the same name:
1
2
3
4
5
6
7
8
int n;//global

void f()
{
    int n;//local
    n = 5; //local
    ::n = 5; //global
}
Jan 14, 2009 at 10:08pm
I was wondering, what are the disadvantages of using global variables? How does c++ keep track of them, etc


Disadvantage is you cannot encapsulate them. So it's hard to put validate the values that might get assigned to them.

If your working on multi-developer projects, this becomes important because you don't want the other developers to mis-use your variable unknowingly.

Also, is there any chance that global variables can change without something acting on them?


No.

Is it best practice to avoid globals?


In Object-orientated development, yes. Because you cannot encapsulate them.

In procedural programming (non-OOD), global variables are ok. But are still typically scoped only to a file level.

Topic archived. No new replies allowed.