Why are we not allowed to have assignment statements in the file scope in C?

前端 未结 2 1446
失恋的感觉
失恋的感觉 2020-12-02 01:33

Why are we only allowed to declare and define variables in global section?Why not include assignment in global section? Example:

#include
int         


        
相关标签:
2条回答
  • 2020-12-02 02:14

    For both questions the answer is the same, in file scope there is no execution of statements or evaluation of expressions, all is done at compile time.

    Other languages (C++ is an example) have a model for dynamic initialization at program startup. This is a complicated issue, e.g because initializers that come from different compilation units don't have a natural ordering among them, but might implicitly depend on each other. SO is an excelent source of information for this question, too.

    C tries to stay simple, simple to use for a programmer and simple to implement for compiler builders.

    0 讨论(0)
  • 2020-12-02 02:16

    We are not allowed to use assignment in file scope because program execution starts from main. Compiler creates _start function which is executed first and then jump to main is made from there. When main returns, control goes back to _start which is having proper exit procedure to terminate program. So anything which is written outside the functions is only meant for the initializations which will be done compile time

    Initialization is different from declaration and assignment. When we initialize variable compiler will make such arrangement that when program execution starts, its value will be what we have initialized. But when we declare a variable, it will be having default initial value specified by its scope. Assignment is done at runtime and not at compile time

    0 讨论(0)
提交回复
热议问题