C中int数组的初始值-为什么?

Leo*_*313 3 c arrays

为什么价值

int array[10];
Run Code Online (Sandbox Code Playgroud)

在函数中声明时为undefined,在0声明为static?时为-initialized

我一直在阅读这个问题的答案,很明显,

int array[10];函数中的[expression ]表示:无需进行任何初始化即可获取10 int大小的内存区域的所有权。如果数组在函数中声明为全局1或静态,则所有尚未初始化的元素都将初始化为零。

问题:为什么这种行为?编译器程序员是否会决定(出于特定原因)?可以使用特定的编译器来做不同的事情吗?

为什么问这个问题我问这个问题是因为我想使我的代码在体系结构/编译器之间可移植。为了确保它,我知道我总是可以初始化声明的数组。但是,这意味着我只会为此操作浪费宝贵的时间。那么,哪个是正确的决定?

PSk*_*cik 6

An automatic int array[10]; isn't implicitly zeroed because the zeroing takes time and you might not need it zeroed. Additionally, you'd pay the cost not just once but each time control ran past the initialized variable.

A static/global int array[10]; is implicitly zeroed because statics/globals are allocated at load time. The memory will be fresh from the OS and if the OS is security conscious at all, the memory will have been zeroed already. Otherwise the loading code (the OS or a dynamic linker) will have to zero them (because the C standard requires it), but it should be able to do it in one call to memset for all globals/statics, which is considerably more efficient than zeroing each static/global variable at a time.

This initialization is done once. Even statics inside of functions are initialized just once, even if they have nonzero initializers (e.g., static int x = 42;. This is why C requires that the initializer of a static be a constant expression).

由于所有全局变量/静态变量的加载时间清零是OS保证的或可以有效实施的,因此它也可能是标准保证的,从而使程序员的生活更轻松。