In C++, it is advisable to declare global variables inside the main program, or outside it, before everything else? I mean, what is the difference between
#include <iostream>
int variable;
int main()
{ //my program
return 0;
}
and
#include <iostream>
int main()
{
int variable;
//my program
return 0;
}
In which case should I use which one?
In the first case variable
is accessible from all other functions in the file (i.e. it has global scope) whereas in the second case it is only accessible from within main
. Generally, it's best to keep the amount of global variables you use to an absolute minimum to avoid polluting the variable space (among several other reasons).
Example:
Local to main,
int main(void) {
int v;
foo();
return 0;
}
void foo() {
v = 5; // compiler error: v not declared in this scope
}
Global,
int v;
int main(void) {
foo();
return 0;
}
void foo() {
v = 5; // compiles, v declared globally
}