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
}
variable
in first case is a global variable. It can be accessed from functions other than, and including, main()
; is guaranteed to live until program executes; and is set to 0 before first use.
In the second example, variable
is a function local variable. It is not initialized to anything unless set by the programmer, can only be accessed within main()
, and will be obliterated before main()
terminates. That last point is not especially important for main()
, but is much more important for other functions.