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.

Ali said:   10 years ago
I couldn't get it. If it takes the last initialization that must be v.b but it is v.a.

Gopi krishna said:   10 years ago
In this the value of v.a is changing, So may be in programs out put is not as expected, if I don't want overwrite of first variable with second initialized value, How can I do that?

Viswakethu.A said:   1 decade ago
SWAP PROGRAM:
a=a+b
b=a-b
a=a-b

For example:
a=10,b=20
1)a=a+b
a=10+20=30
2)b=a-b
b=30-20=10
3)a=a-b
a=30-10=20

So, a = 20

Maddy said:   1 decade ago
Nice expalanation vedavathi.

Nadeem said:   1 decade ago
@rajadurai

Union may have collection of different datatypes. so, it allocates the memory of the largest data type.

Ex:

union xyz{
int x;
float y;
double z;
};

It allocates only 8 bytes for whole. Agree?

Jyoti pandey said:   1 decade ago
Rajadurai is wrong.
Union not allocate for large memory size.
It allocate the last overrided value Whether it is large or small

Karpakam said:   1 decade ago
Good explanation Viswakethu.A

Vandana said:   1 decade ago
At first union stores large value into memory, so we Will get 20 as output.

Ashish said:   1 decade ago
Good answer Dinesh.....

Atul tailwal said:   1 decade ago
I agree to Rishabh


Post your comments here:

Your comments will be displayed after verification.