After running this code:
#include <stdio.h>
int x;
int main(void)
{
printf("%d\n",x);
return 0;
}
int x=5;
I expected the output should be 0
. Because of the sequence control structure of the program int x;
should be executed first and then 0
is printed and finally int x=5;
should be executed. But it is giving the output 5
.
How is the program accesses 5
for the x
in printf
?
The first acts as a forward declaration, and the later acts as the actual definition.
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.
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.