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

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

Abhijeet Apar said:   9 years ago
I agree, with your answer but in the previous question, we got two values and both are also of same variable type. Then why this condition is not satisfied in that question? Please clear my doubt.

Palaniarjun said:   9 years ago
Hi, friends

#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
v.a=100;
v.b=10;
printf("%d\n", v.a);
return 0;
}
---------------------------------------
Out put =10
------------------------------------------

Union allocates highest memory location for the data type(int,float,char) in these data type float has the highest memory so union allocate 4 bytes. And union store only one value it override the previous value,so it produces the last declaration or initialization value.

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

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

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

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

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

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

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.


Post your comments here:

Your comments will be displayed after verification.