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

Siraj Ansari said:   1 decade ago
There are two concept first one is union by default preferred higher memory allocation, and second one is union has print single value and that value should be higher value.

Smitha said:   1 decade ago
#include<stdio.h>
int main()
{
union var
{
int a, b, c;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.c);
return 0;
}

Even if we add a third variable 'c' to the union and try to print it would output the same value =20 since it will always output the last value in such cases.

Alfaz raza khan said:   1 decade ago
All the members of union are stored at the same address, this means there is only one common memory. Hence in this case initially,

v.a = 10;//10 will be stored.
v.b = 20;//at the same address 20 will be stored.

Mitha mazumdar said:   1 decade ago
But 'c' cannot create objects as java does so how it is possible?

Monichoron said:   1 decade ago
Union will take only the last value and other will be overwrite such as

main a
{

union v

{
int a,b,c;
}

union v h;
h.a=4;h.b=6;h.c=4;
printf("%d %d",h.a,h.c);

}

It will print only the last value 3

Output will be 3 3

Gunjali agarwal said:   1 decade ago
#include<stdio.h>
int main()
{
printf("Weclome to IndiaBIX.com..!");
union var
{
int a;
float b;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.a);
return 0;
}

Output: Garbage value.

Nagarjuna said:   1 decade ago
In union all the variables allocated in same memory no separate bit fields. So it takes the highest value of the allocated numbers in the memory.

Vinitha said:   1 decade ago
I understood the union concept.

Anu said:   1 decade ago
Since union shares the same memory space, the value gets overwritten.

Abhishek said:   10 years ago
main a
{

union v

{
int a,b,c;
}

union v h;
h.a=4;h.b=6;h.c=4;
printf("%d %d",h.a,h.c);

}

It will print only the last value 3.

Output will be 3 3.

How the output 3 3 is come? I don't understand about this output.


Post your comments here:

Your comments will be displayed after verification.