Is it possible that a variable declared after the main has file scope?

空扰寡人 提交于 2019-11-29 14:31:00

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!