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;
}
Discussion:
83 comments Page 2 of 9.
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
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
Rishabh said:
1 decade 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.
Vinay said:
1 decade ago
Ya I agree with you rishabh.
Divya said:
1 decade ago
Good answer Srividhya & Rishabh
Atul tailwal said:
1 decade ago
I agree to Rishabh
Ashish said:
1 decade ago
Good answer Dinesh.....
Vandana said:
1 decade ago
At first union stores large value into memory, so we Will get 20 as output.
Karpakam said:
1 decade ago
Good explanation Viswakethu.A
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
Union not allocate for large memory size.
It allocate the last overrided value Whether it is large or small
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?
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?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers