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

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.

Suprajanarayan said:   1 decade ago
What will be defined at last that will be printed?

TALLURI NARESH said:   1 decade ago
Memory is allocated the max size of the elements.

Sayantan said:   1 decade ago
Suppose in Union we need other variable such as name, marks and roll, then how will it be possible to work with different variable if it replaces earlier variable values?

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

Ganesh Jagtap said:   1 year ago
Union : Holds multiple members with different data types, and all members share the same memory location.

So, in this case, latest stored data has the highest priority.

Venkat g said:   7 years ago
Thanks @KPS Lubana.

Mads said:   8 years ago
Why the output is garbage value for the following program? Can anyone explain?

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

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

Reshma said:   9 years ago
Union allocates memory for the large memory size.


Post your comments here:

Your comments will be displayed after verification.