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 4 of 9.
Janardhan reddy said:
1 decade ago
In C compiler allocates 2 bytes of memory to union and int needs 2 bytes. In this way first value is deleted and only 2nd value is present, in place of first value. So output is 20.
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?
Siraj Ansari said:
1 decade ago
There are two concept first one is union by default preferred higher memory allocation, and second one is union has print single value and that value should be higher value.
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?
Ganesh Jagtap said:
1 year ago
Union : Holds multiple members with different data types, and all members share the same memory location.
So, in this case, latest stored data has the highest priority.
So, in this case, latest stored data has the highest priority.
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.
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.
Nagarjuna said:
1 decade ago
In union all the variables allocated in same memory no separate bit fields. So it takes the highest value of the allocated numbers in the memory.
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.
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
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers