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

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)

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)

Ganesh Jagtap said:   1 year 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.


Post your comments here:

Your comments will be displayed after verification.