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

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.

Nitish anand said:   1 decade ago
Union allocate memory only for which have large memory size.

Sayantan said:   1 decade ago
Suppose in Union we need other variable such as name, marks and roll, then how will it be possible to work with different variable if it replaces earlier variable values?

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

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

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.

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.

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.

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.

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.


Post your comments here:

Your comments will be displayed after verification.