Why's initializing a global variable with return value of a function failing at declaration,but works fine at file scope?

后端 未结 5 2138
名媛妹妹
名媛妹妹 2020-12-19 04:51

An 80k reputation contributor R.. told me on SO that we can\'t initialize global variables with the return value of a function as that\'s not c

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 05:13

    The reason behind it is that in order to determine a value produced by a function one needs to execute code, and that there is no code execution done in C when initializing static and global variables.

    Compiler and linker work together to prepare a byte image of the global memory segment: the compiler provides the values, and the linker performs their final layout. At runtime, the image of the segment is loaded in memory as is, without further modifications. This happens before any code gets executed, so no function calls can be made.

    Note that this does not mean that it is not possible for some technical reason, only that C designers decided against doing it. For example, C++ compiler generates a code segment that calls constructors of global objects, which gets executed before the control is passed to main().

提交回复
热议问题