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.

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)

Mounisha said:   7 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)

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

Keerthana said:   7 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)

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

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

Alex said:   1 decade ago
As the principle of Union- All the variable shares the same memory locations and at time only one value can be accessed so memory allocated by the highest demand of variable so that other variable also can use that.

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.


Post your comments here:

Your comments will be displayed after verification.