C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Find Output of Program (Q.No. 2)
2.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    union var
    {
        int a, b;
    };
    union var v;
    v.a=10;
    v.b=20;
    printf("%d\n", v.a);
    return 0;
}
10
20
30
0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
83 comments Page 7 of 9.

Gopi krishna said:   10 years ago
In this the value of v.a is changing, So may be in programs out put is not as expected, if I don't want overwrite of first variable with second initialized value, How can I do that?

Ali said:   10 years ago
I couldn't get it. If it takes the last initialization that must be v.b but it is v.a.

Rashed said:   10 years ago
I didn't understand how it becomes 20 it must be 10.

Gopi krishna said:   10 years ago
#include<stdio.h>

int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
v.b=20;
printf("%d %u %u\n", v.a,&v.a,&v.b);
return 0;
}

Output: 20 4291065820 4291065820. Hence only a, b both referring to same address.

Olaf said:   9 years ago
The output is just some garbage number.

Sanju said:   9 years ago
Actually in unions. The size of union corresponds to the length of the longest member. Thank you.

Praveena said:   9 years ago
Nice explanation. Thank you @Srividhya.

Bhoomika said:   9 years ago
Yes, I will agree with you @Rishabh.

Arunya said:   9 years ago
I also agree with Srividhya.

Vasant said:   9 years ago
I also agree with Srividhya.


Post your comments here:

Your comments will be displayed after verification.