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:
78 comments Page 4 of 8.

Aaryan said:   8 years ago
Hi friends, some guys have a problem that how we got a 512?

So the answer is like.
From right to left start from 1 and double the size after ++.
For eg...... 512 256 128 64 32 16 8 4 2 1

Binary is = 00000010 00000011.
512*1+0+0+0+0+0+0+0+2*1+1*1.
=512+2+1.
=515.

Ayush said:   9 years ago
How can we get the size of the entire union by u.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?

Yamani said:   8 years ago
Thank you for your explanation. It helps me a lot @Nandini.

Anonymous said:   9 years ago
If u.i displays the size of the Union then how to display the 'i' value?

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

Can anyone answer it? please.

Prakash said:   9 years ago
Could anyone please explain me the output of this program?

#include<stdio.h>
int main()
{
union a
{
int i;
char ch;
};
union a u;
printf("%d,%f\n",sizeof(u),u.i);
return 0;
}

o/p: 4 23

Ritika said:   1 decade ago
Please explain in detail why is it giving 515 as the size of the union?

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?

Radhika said:   1 decade ago
But why do u.i gives the size of union?


Post your comments here:

Your comments will be displayed after verification.