C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 9)
9.
What is the output of the program
#include<stdio.h>
int main()
{
    int a[5] = {2, 3};
    printf("%d, %d, %d\n", a[2], a[3], a[4]);
    return 0;
}
Garbage Values
2, 3, 3
3, 2, 2
0, 0, 0
Answer: Option
Explanation:
When an automatic array is partially initialized, the remaining elements are initialized to 0.
Discussion:
38 comments Page 2 of 4.

Sam said:   1 decade ago
It will show garbage values if we do not partially initialize the array.

And referring c programming language by dennis ritchie, it says that only extern and static variables are initialized as zero by default?

Praj said:   6 years ago
If an array is declared globally then uninitialized index value will be automatically set to zero. If the array is declared internally then it contains garbage value. Right?
(1)

Rohit said:   2 years ago
Ideally, it depends on the compiler to generate code to initialize a partially initialized array or not. Sometimes to save time it is not necessary to initialize it to zero.

Ananya said:   1 decade ago
@Raghav.

But When no initialization is given then also it is showing the output as zero. But as you said it should print some garbage value. Then why it is happening?

Shanme said:   9 years ago
When we declare any array function, it will assign it s value start from a[0], a[1],...................

Eg:
int a[4]={1,2,3,4,5};
then
a[0]=1,a[1]=2, ........a[4]=5.

Siva said:   1 decade ago
As per gcc compiler it will take garbage values where non existing elements and existing elements a[0] = 2, a[1] = 3, a[3] = garbage value, a[4] = garbage value.

Jayakumar said:   9 years ago
Every index value is Start is 0.

So, int a[5]={2,3}
a[0]={2}
a[1]={3}
a[2]={0}

Automatically initialized the value is called zero.
So answer is called 000.

Penchal said:   1 decade ago
The arry function automatically takes the free values as '0'
ex:-
arr[4]={1,2};
It will store the arry as arry[4]={1,2,0,0}

Vasu said:   8 years ago
There is a[5] = {2,3,0,0,0}.
i.e. a[0] = 2.
a[1] = 3.
a[2] = 0.
a[3] = 0.
a[4] = 0.
So, the value of a[2]=0, a[3]=0 & a[4]=0.
(1)

SUNIL(THE PAIN) said:   1 decade ago
Why is not showing the garbage value, if we do not partially initialize the array?

I didn't get from the above discussion.


Post your comments here:

Your comments will be displayed after verification.