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.

Shobana said:   2 decades ago
How it will print 20?

Srividhya said:   2 decades ago
Because union can initialize only one variable at a time. It overwrites the memory with binary value of 20 where it was initialized with binary value of 10 before.

It takes the last initialized value of its member variables.

Rasagnaa said:   2 decades ago
Yes I agree with srividya.

Rajadurai said:   2 decades ago
Union allocate memory only for which have large memory size.

Vedavathi said:   1 decade ago
In union all the members should be different data types. If two variables having the same datatype should be overwrited in memory. Here both are int values only, so first 10 is overwrited by 20. So 20 will be displayed.

DINESH said:   1 decade ago
Union allocate memory for the variables which has highest.

Size only once, and all other variables are over write in it.

Hence the above program memory for int allocate once, first it store 'a' variable value later it over write with recent initialize 'b'.

Value, so the out put will be 'b' value.

Vijayabaskar said:   1 decade ago
Ya! agree with Sreevidhaya

Mari said:   1 decade ago
Good answer srividhya.

Pradeep said:   1 decade ago
In unions, we are getting data from particular allocated memory for only one variable, in doesnt matter about datatype. We can awaken only one variable in union at a time and getting overriden data. That is "b" value.

Elakkiya said:   1 decade ago
In union memory allocated for the current value will be excuted during the run time. So in this program the current value is 20 so it print the value as 20.


Post your comments here:

Your comments will be displayed after verification.