Global Variables

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?
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.
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
}
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.