为什么这个数组的所有剩余值都初始化为零? [英] Why is this array having all remaining values initialized to zero?
问题描述
你好,我是C编程语言的初学者,最近我开始学习数组,我研究过默认情况下int数组中的所有值都是垃圾.
Hello I am a beginner in C programming language, recently i started learning arrays, I have studied that by default all values in an int array are garbage.
那为什么我在这两种情况下得到不同的值.
Then why i am getting different values in these two cases.
案例 1
int arr[5];
在这种情况下,从 arr[0] 到 arr[4] 我们将有垃圾值,但在下一种情况下.
in this case from arr[0] till arr[4] we will have garbage values, but in next case.
案例 2
int arr[5] = {1};
在这种情况下,arr[0] 的值为 1,其余从 arr[1] 到 arr[4] 的值为 0.
in this case arr[0] will have a value 1 and remaining from arr[1] to arr[4] will have value 0.
我的问题是,如果在 case-1 中每个未初始化的数组位置都有垃圾值,那么为什么在 case-2 中剩余的未初始化数组位置的默认值是 0.
My question is that, When in case-1 each un-initilized array locations are having garbage valeus then why in case-2 remaining un-initilized array locations are having 0 as default value.
推荐答案
C11 6.7.9 Initialization p19 涵盖了这个(我的重点)
C11 6.7.9 Initialization p19 covers this (my emphasis)
初始化应按初始化列表顺序进行,每个初始化为特定子对象提供覆盖任何先前列出的相同子对象的初始化程序;151) 所有未显式初始化的子对象应进行初始化与具有静态存储持续时间的对象隐式相同.
The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.
6.7.9 p10 部分指出
如果一个具有静态或线程存储持续时间的对象不是显式初始化,然后...如果它具有算术类型,则为初始化为(正或无符号)零;
If an object that has static or thread storage duration is not initialized explicitly, then...if it has arithmetic type, it is initialized to (positive or unsigned) zero;
这篇关于为什么这个数组的所有剩余值都初始化为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!