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?
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 withinmain()
, and will be obliterated beforemain()
terminates. That last point is not especially important formain()
, but is much more important for other functions.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 withinmain
. 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,
Global,