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

Sjohnson said:   8 years ago
@All.

If sizeof(int) > 4 then the upper bits of a.i is not initialized and the value of u.i can be greater than 0x0203. For example, the 64-bit compiler on my system produces the value 0x7c0203.

However, if I set u.i = 0 before setting u.ch[0], u.ch[1] then it works.

Rashmi said:   9 years ago
Why u.i would print size of the union? What exactly u.i means?

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

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

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

Can anyone answer it? please.

Prakash said:   8 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

Naziya said:   9 years ago
Explanation to the given question is as follows. As we know union size is the biggest size of its element, hence integer is considered to be the biggest.

Here integer is considered to be 4 bytes which are equal to 32 bits (GCC compiler). The memory allocation is as follows. 0000000000000000000000010000000011.

Hence from the above figure u.ch[0] = 3 & u.ch[1]=2.

As the character is of 1 byte.

So in that 4 bytes itself u.ch[0] and u.ch[1] can be occupied, as we are considering the biggest element to b integer, in other words, memory is shared.

So when we see u.i value is equivalent to 512 (the value at 10th bit) +2 (the value at 1st bit) +1 (the value at 0th bit). Therefore 512 + 2 + 1 = 515.

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?

Ayush said:   9 years ago
How can we get the size of the entire union by u.i?

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


Post your comments here:

Your comments will be displayed after verification.