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 8 of 9.
Vinay said:
1 decade ago
Ya I agree with you rishabh.
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.
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
Elakkiya said:
1 decade ago
In union memory allocated for the current value will be excuted during the run time. So in this program the current value is 20 so it print the value as 20.
Pradeep said:
1 decade ago
In unions, we are getting data from particular allocated memory for only one variable, in doesnt matter about datatype. We can awaken only one variable in union at a time and getting overriden data. That is "b" value.
Mari said:
1 decade ago
Good answer srividhya.
Vijayabaskar said:
1 decade ago
Ya! agree with Sreevidhaya
DINESH said:
1 decade ago
Union allocate memory for the variables which has highest.
Size only once, and all other variables are over write in it.
Hence the above program memory for int allocate once, first it store 'a' variable value later it over write with recent initialize 'b'.
Value, so the out put will be 'b' value.
Size only once, and all other variables are over write in it.
Hence the above program memory for int allocate once, first it store 'a' variable value later it over write with recent initialize 'b'.
Value, so the out put will be 'b' value.
Vedavathi said:
1 decade ago
In union all the members should be different data types. If two variables having the same datatype should be overwrited in memory. Here both are int values only, so first 10 is overwrited by 20. So 20 will be displayed.
Rajadurai said:
2 decades ago
Union allocate memory only for which have large memory size.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers