A global variable can be accessed from anywhere in your program. They are declared outside of a function, method or class. A local variable can only be accessed from within the block of code in which it exists. For example, in the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// NOTE: This code is poorly written, please don't write your programs like this, it's just for examples sake :)
#include <iostream>
int i;
int main(void) {
for(i = 0; i < 100; i++) {
int x;
std::cout << x++ << std::endl;
}
std::cout << x << std::endl; // compiler error
std::cout << i << std::endl; // no error :)
return 0;
}
x is a local variable. The memory allocated to the variable is cleared at the end of the for loop, and the variable no longer exists. i is a global variable, so you can access it whenever you want from any function, as is shown. It's best to avoid global variables when you can :)
Here's a related question:
If global variables can be accessed from any function, they seem to be advantageous over local variables. I've always known that I should avoid global variables, but why? Is it simply to avoid overlapping names? In a single-file project, this doesn't seem like it'd be a problem.
Stewbond, from what I know, the reason why global variables are considered bad is because, when you have a huge .cpp file, sometimes you accidently tweaked that global variable in the way that it changed the purpose of the usage of that global variable throughout the program.
Say, you used that local variable for 10 purposes. When you change the value of that variable for the 10th purpose, all of the other 9 past usages of the variable will be altered too, and so there might be an error.
It's like there's a high chance of human error of using global variables. But, if you are super careful, sure, it's not bad to use them. But in large programs, the chances of human error increases significantly.
Well, I'm new too, but that's what I've learned about why not to use them.