Is it possible that a variable declared after the

2019-01-28 04:11发布

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?

3条回答
时光不老,我们不散
2楼-- · 2019-01-28 04:24

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.

查看更多
Fickle 薄情
3楼-- · 2019-01-28 04:26

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.

查看更多
叛逆
4楼-- · 2019-01-28 04:32

The first acts as a forward declaration, and the later acts as the actual definition.

查看更多
登录 后发表回答