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.

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

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.

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?

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.

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

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

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.

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.

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

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


Post your comments here:

Your comments will be displayed after verification.