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 5 of 9.

Jyoti pandey said:   1 decade ago
Rajadurai is wrong.
Union not allocate for large memory size.
It allocate the last overrided value Whether it is large or small

Sushil chavan said:   1 decade ago
I agree with @Srividhya. Union can locate only one variable at a time. Hence it takes the last variable value which is define.

S Saha said:   4 years ago
Overlapping.

By definition of a union: you can't simultaneously use v.a and v.b because both fields share the same address.
(2)

Abhay said:   1 decade ago
If in above question a is initiallised with 20 and b with 10 then
o/p becomes 10(the last updated value is 10)..... ..!!!!

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

Ankita gaba said:   1 decade ago
If in above question a is initiallised with 20 and b with 10 then what will be the o/p?

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.

Sandy said:   1 decade ago
What if the data types are different in union?

ex: union var{
int a;
double b;
}

Vignesh said:   8 years ago
Thanks for all the explanation. Thanks for all your help, I understand it now.

Vandana said:   1 decade ago
At first union stores large value into memory, so we Will get 20 as output.


Post your comments here:

Your comments will be displayed after verification.