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 3 of 9.
Maddy said:
1 decade ago
Nice expalanation vedavathi.
RamDas said:
1 decade ago
Sridivya your answer is good
Doni said:
1 decade ago
Srivdiya n Risbah answers are good.
Shikha said:
1 decade ago
All variable inside in the union share the same memory area so all modification done in the same memory hence answer is the last updated value i.e. 20.
Ankita gaba said:
1 decade ago
If in above question a is initiallised with 20 and b with 10 then what will be the o/p?
Abhay said:
1 decade ago
If in above question a is initiallised with 20 and b with 10 then
o/p becomes 10(the last updated value is 10)..... ..!!!!
o/p becomes 10(the last updated value is 10)..... ..!!!!
Smit said:
1 decade ago
Good Logic Bro.
But it also in structure?
But it also in structure?
Sai said:
1 decade ago
The difference between union and structure is
Structure used as prototype in creating objects with same memory, it can not compress the memory.
struct a{ int a; float b; }obj;
Here obj is having 6 bytes in memory.
Where as for union, it allocates largest memory among all datatypes defined in the union.
union a{ int a; float b;}obj;
Here obj is having 4 bytes instead of 6 Bytes.
So, union utilizes largest memory assigned to variable among all variables and it will be used for all its operations.
Structure used as prototype in creating objects with same memory, it can not compress the memory.
struct a{ int a; float b; }obj;
Here obj is having 6 bytes in memory.
Where as for union, it allocates largest memory among all datatypes defined in the union.
union a{ int a; float b;}obj;
Here obj is having 4 bytes instead of 6 Bytes.
So, union utilizes largest memory assigned to variable among all variables and it will be used for all its operations.
Bips said:
1 decade ago
I think it will give compile error...
cause
v.a=10;
v.b=20;
printf("%d\n", v.a);
since v.b=20 overwrites the value v.a=10
but program is trying to print the value which doesnot exist.
...
..
.
correct me if i m wrong...
cause
v.a=10;
v.b=20;
printf("%d\n", v.a);
since v.b=20 overwrites the value v.a=10
but program is trying to print the value which doesnot exist.
...
..
.
correct me if i m wrong...
Sss said:
1 decade ago
Good Explanation...
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers