C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Find Output of Program (Q.No. 1)
1.
What will be 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
515, 515, 4
Answer: Option
Explanation:

The system will allocate 2 bytes for the union.

The statements u.ch[0]=3; u.ch[1]=2; store data in memory as given below.

Discussion:
40 comments Page 4 of 4.

Ramya said:   1 decade ago
hey i cant get ur answer ,plz explain me how the value of u.i is assigned

Pavani said:   2 decades ago
How to get the value of u.i ?

Sundar said:   1 decade ago
@Raju Kumar:

In TurboC it prints 0, 0, 0, 0 (as expected).

But in GCC it prints 0, 0, 0, 134217728 (last value is unexpected).

It is due to the platform dependency of compilers.

Because for 'int' TurboC (under DOS) reserves two bytes only. But in Linux GCC reserves 4 bytes.

You have initialized/assigned only three bytes (u.ch[0], u.ch[1], u.ch[2]) of the reserved bytes to 0 (zero). The remaining one byte (1 out of 4) not yet assigned with any value. So it may have some junk/garbage value.

So while printing the u.i, it prints the garbage value.

If the change your code for union as give below, the above problem will not occur.

union a
{
short i; // change 'int' --> 'short'
char ch[3];
};

Hope this will help you. Have a nice day!

SATHYA said:   1 decade ago
@Sundar

Your explanation is the best one. THANKS.

Krishna said:   1 decade ago
Give full information according (2)(3)=512

Ashish said:   1 decade ago
@Sundar

why 20 comes as value of u.ch[2] in output?
I understand about garbage value. cant understand about u.ch[2]

#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, %d\n", u.ch[0], u.ch[1], u.ch[2], u.i);
return 0;
}
Ans is 3, 2, 20, some garbage value.

Ashwini said:   1 decade ago
@Ashish

When I compile it in Turbo c++ IDE

It has given output as: 3 2 0 50

not u.ch[2] as 20

and I think 50 as garbage value, So how u.ch[2] as 0 ?

Jyoti pandey said:   1 decade ago
Thanks guys really great.

Priyu said:   1 decade ago
@ ashwni
In ashish question the value of the u.i should be 515?

Ganesanttl said:   1 decade ago
Is there any restriction to use char in union should contain one int value ? suppose replaced int i to any other (char i, float i. ) what happen ?


Post your comments here:

Your comments will be displayed after verification.