Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

c - Why is this array having all remaining values initialized to zero?

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.

Case-1

int arr[5];

in this case from arr[0] till arr[4] we will have garbage values, but in next case.

Case-2

int arr[5] = {1};

in this case arr[0] will have a value 1 and remaining from arr[1] to arr[4] will have value 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C11 6.7.9 Initialization p19 covers this (my emphasis)

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.

Section 6.7.9 p10 states that

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...