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

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

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

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.

David Rajesh said:   1 decade ago
Dear All,

#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;
}

OutPut : 20
-----------------------------------

#include<stdio.h>
int main()
{
union var
{
int a, b;
};
union var v;
//v.a=10;
v.b=20;
v.a=10;
printf("%d\n", v.a);
return 0;
}

OutPut : 10

Here we came to know that, union allocates memory of 2 bytes for an integer.
In 1st prg we have assigned as 20 and in 2nd prg we have assigned as 10. i.e., when you print the address of both v.a and v.b the address are same, because union allocates the largest memory size for 2bytes only.

Rahul said:   1 decade ago
Above program memory for int allocate once in union, first it store 'a' variable in memory value, later it OVERRIDE with RECENT initialize 'b'.

Value, so the output will be 'b' value.

Nalu said:   1 decade ago
When the data types are different the highest datatype size will be assigned to union and only one variable can be accessed at a time. And it overwrites the same location again and again as long as you use the variables of union. !:).

Sandy said:   1 decade ago
What if the data types are different in union?

ex: union var{
int a;
double b;
}

Atul kumar said:   1 decade ago
Union allocates single memory for all variables, which has the highest size. So first value(10) will be overwrite with second value(20) because memory location is one. Hence output will be 20.

Sathya said:   1 decade ago
How it will print 20? I can't understand please explain it.

Spurthi said:   1 decade ago
Answer is 20 because in union if we enter two values then the first value is replaced by another value so here 10 is replaced by 20.


Post your comments here:

Your comments will be displayed after verification.