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

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

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

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.

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 ?

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

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.

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

Moorthy said:   1 decade ago
Please explain this program fully.

Wikiok said:   1 decade ago
#include<stdio.h>
union
{
int a;
char c[2];
} myu;
int main()
{
printf("%d",sizeof(myu)); //Size of the union in memory. 4
return 0;
}
-----------------
sizeof(union) = sizeof( largest element )

Anu said:   1 decade ago
Please could anyone explain me this one I cant get it how. I gives this value?and how to calculate the size of union?


Post your comments here:

Your comments will be displayed after verification.