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

Ganesh Jagtap said:   9 months 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.

Kalai said:   2 years ago
Union: a collection of different data items stored in a same memory location.

-> last store data is the first priority. So 20 is printed because all data is stored in the same memory location.
(8)

S Saha said:   3 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)

Karan said:   6 years ago
How it will print 20? I am not getting, please anyone tell me.
(1)

Mounisha said:   6 years ago
The union will allocate for all datatypes in the same memory location, the only structure will allocate the separate memory.

The location for each data types. So, it can initialize only one value at a time v.b=20 has replaced the value of v.a=10, So it will be stored in address space 20.
(3)

Keerthana said:   6 years ago
In union, all the variables share the same address space.

Since union can initialize one value at a time,the second assignment statement i.e..,v.b=20 replaces the previous value of v.a=10. So, finally, 20 is stored in union address space which will be shared by both variables a & b.
(2)

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

Kps lubana said:   7 years ago
0 is the Answer.
(1)

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.


Post your comments here:

Your comments will be displayed after verification.