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 5 of 9.
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?
Nitish anand said:
1 decade ago
Union allocate memory only for which have large memory size.
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.
Value, so the output will be 'b' value.
Nalu said:
1 decade ago
When the data types are different the highest datatype size will be assigned to union and only one variable can be accessed at a time. And it overwrites the same location again and again as long as you use the variables of union. !:).
Sandy said:
1 decade ago
What if the data types are different in union?
ex: union var{
int a;
double b;
}
ex: union var{
int a;
double b;
}
Atul kumar said:
1 decade ago
Union allocates single memory for all variables, which has the highest size. So first value(10) will be overwrite with second value(20) because memory location is one. Hence output will be 20.
Sathya said:
1 decade ago
How it will print 20? I can't understand please explain it.
Spurthi said:
1 decade ago
Answer is 20 because in union if we enter two values then the first value is replaced by another value so here 10 is replaced by 20.
Prashanth said:
1 decade ago
David Rajesh your explanation is good
Srihari 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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers