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 2 of 8.

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

Sahana said:   1 decade ago
Upto 512 calculation I can understand. But what about adding 2+1 with 512. So that we get the ans as 515. Please explain this.

Deepak said:   1 decade ago
@Sahana

Its like multiplying contents inside memory location with index....like 512*1(see fig)...all other are zero......2*1 & 1*1

Sushma said:   1 decade ago
First of all why should we consider 8 bits to calculate size of union. Why not 16 bits or something else then the answer will change ?

Nutan said:   1 decade ago
u.ch[0] = 3;
u.ch[1] = 2;

The Above two statements is fine but when u try to access i value, how it becomes 515 sum of index.

Sravan said:   1 decade ago
I can't able to get why 2+1 is added to 512. Can any one please explain briefly ?

Jignesh said:   1 decade ago
How is it possible?
I is the variable and how 515 came?

Alisha said:   1 decade ago
Please explain how we get value of i?

Avinash said:   1 decade ago
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;

u.i=11;

printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}

Try output for this program.

Nandini said:   1 decade ago
Hi friends,

Here ch[0]=3 the binary value of 3 = 00000011=011 and ch[1]=2 the binary value of 2=010=00000010.

Now we can call the size of union i.e, 00000010 00000011.

See the fig so 1*1+2*1+512*1=515.

We are taking only 512, 1 and 2 because at these places only we have 1's remaing places we have zero. If we take the remaing also it'll multipled by 0 anyway we can get 0 for that values.


Post your comments here:

Your comments will be displayed after verification.