C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 10)
10.
What is the output of the program?
#include<stdio.h>
int main()
{
    union a
    {
        int i;
        char ch[2];
    };
    union a u;
    u.ch[0] = 3;
    u.ch[1] = 2;
    printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
    return 0;
}
3, 2, 515
515, 2, 3
3, 2, 5
None of these
Answer: Option
Explanation:

printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i); It prints the value of u.ch[0] = 3, u.ch[1] = 2 and it prints the value of u.i means the value of entire union size.

So the output is 3, 2, 515.

Discussion:
77 comments Page 5 of 8.

Kuldip said:   1 decade ago
I read all question and answer but still I can't get answer of why union share common memory to all data elements.

Deepika said:   9 years ago
union a u;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);

Can anyone explain these both lines?

Dhivya said:   1 decade ago
I confused that why we have to calculate the size of the union for i. Why it is not 0 like in structure?

Sanju said:   9 years ago
Every time I run the program, it didn't give 515 for me. It's giving some garbage value. Please help me.

Phani said:   1 decade ago
Hi nandini good explanation.

I broked my head for understanding. Your explanation helped me.

Thk you.

Punya said:   9 years ago
Please check by running the same program with c compiler, the Garbage value will be printed for i.

Preethi said:   8 years ago
Why we find the size of the union in coding doesn't mention about size only the variable value?

Ravi said:   1 decade ago
Why we are assigning the 515 to the int i?

Why 'i' is not having any other value(like 0 or 1)?

Anonymous said:   8 years ago
Why u. i prints the size of the Union in the first place?

Can anyone answer it? please.

Manjiree said:   6 years ago
Please can you explain in detail how it will calculate the entire size of the union?
(1)


Post your comments here:

Your comments will be displayed after verification.