本文介绍了为什么用函数的返回值初始化全局变量在声明时失败,但在文件范围内工作正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

80k 声誉贡献者 R.. 在 SO 上告诉我,我们不能用函数的返回值初始化全局变量,因为它不被视为常量,并且全局变量必须用一个常量初始化.他的话是真实的,我得到了这个程序的以下错误,正如预期的那样 - initializer element is not a constant.这是程序:

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 considered a constant,and global variables must be initialized with a constant.And true to his words,I get the following error for this program as expected-- initializer element is not a constant.Here is the program:

#include<stdio.h>
int foo();
int gvar=foo();  //ERROR

int main()
{
printf("%d",gvar);
}

int foo()
{
 return 8;
}

但是在这种情况下,我只是不明白为什么上述程序的后续更改版本根本没有显示任何错误并且工作正常.在第二个程序中,我用返回值初始化相同的全局变量same 函数 foo().你能告诉我导致这种结果变化的严格技术原因是什么?为什么用函数的返回值初始化全局变量它是导致错误的声明,但是在函数内完成具有相同返回值的相同初始化工作正常?

But in this context,I just don't understand why the followed altered version of the above program shows no error at all and works fine.In this second program,I am initializing the same global variable with the return value of the same function foo().Can you tell me what is the rigorous technical reason for this variation in results?Why is initializing the global variable with the return value of a function at it's declaration causing error but the same initialization with the same return value works fine when done from within a function?

#include<stdio.h>
int foo();
int gvar;

int main()
{
gvar=foo();
printf("%d",gvar);
}

int foo()
{
return 8;
}

输出 8

推荐答案

背后的原因是为了确定一个函数产生的值需要执行代码,而在 C 中没有代码执行的时候初始化静态和全局变量.

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.

请注意,这并不意味着由于某些技术原因不可能,只是 C 设计者决定不这样做.例如,C++ 编译器生成一个调用全局对象构造函数的代码段,该代码段在控件传递给 main() 之前执行.

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().

这篇关于为什么用函数的返回值初始化全局变量在声明时失败,但在文件范围内工作正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:33