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

Alfaz raza khan said:   1 decade ago
All the members of union are stored at the same address, this means there is only one common memory. Hence in this case initially,

v.a = 10;//10 will be stored.
v.b = 20;//at the same address 20 will be stored.

Smitha said:   1 decade ago
#include<stdio.h>
int main()
{
union var
{
int a, b, c;
};
union var v;
v.a=10;
v.b=20;
printf("%d\n", v.c);
return 0;
}

Even if we add a third variable 'c' to the union and try to print it would output the same value =20 since it will always output the last value in such cases.

Siraj Ansari said:   1 decade ago
There are two concept first one is union by default preferred higher memory allocation, and second one is union has print single value and that value should be higher value.

Shabana said:   1 decade ago
Because union can initialize only one variable at a time.it will only one members that is greatest the number and last initialized members in aove programe v.a=10;

v.b=20; it will only 20 becoz union can occupy last members that is greatest number.

Janardhan reddy said:   1 decade ago
In C compiler allocates 2 bytes of memory to union and int needs 2 bytes. In this way first value is deleted and only 2nd value is present, in place of first value. So output is 20.

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.

Remember me!! said:   1 decade ago
Here you can see the difference:

You have to print value of 'a' before 'b' get declared to 20. Because union always display the datatype having larger memory.

#include<stdio.h>

int main()
{
union var
{
int a, b;
};
union var v;
v.a=10;
printf("%d\n", v.a);
v.b=20;

getch();
return 0;
}

The reason why union is used means it hold very less memory than structure it doesn't waste memory. I believe its a good think.

Sushil chavan said:   1 decade ago
I agree with @Srividhya. Union can locate only one variable at a time. Hence it takes the last variable value which is define.

Suprajanarayan said:   1 decade ago
What will be defined at last that will be printed?

TALLURI NARESH said:   1 decade ago
Memory is allocated the max size of the elements.


Post your comments here:

Your comments will be displayed after verification.