After running this code:
#include
int x;
int main(void)
{
printf(\"%d\\n\",x);
return 0;
}
int x=5;
I expected t
Global variables are initialised before main()
runs. That means that it's entirely possible for a function to access something which appears after it in the file, as long as it's visible (i.e. forward declared).
With that said, you shouldn't really have multiple declarations for the same variable in one file. It could lead to confusion (mainly for the programmer) about what and where it's actually initialised.
EDIT: To clarify, functions/variables in global scope are not executed like a sequence of statements inside a function. The location of the function's declaration/definition has absolutely no bearing on when it gets called in relation to any other code. It only determines what parts of the surrounding scope are visible to it. In your case, this means main()
does not get called in between your two int
lines. It gets called by the runtime when it's finished all other initialisation.
Variable default values declared outside of functions get set before main ever runs. So what you are seeing is the correct behavior. Same goes for variables declared in other source files.
The first acts as a forward declaration, and the later acts as the actual definition.