+ 1
What's the output of this program and How?
#include <stdio.h> int main() { union var { int a, b; }; union var v; v.a = 10; v.b = 30; printf("%d\n", v.a); return 0; }
1 Respuesta
+ 1
An union is a specific data type which size is the biggest value of his member. Here, assuming you're compiling with gcc on a 32bits computer, the union 'var' will have a size of 4 bytes.
The memory inside an union is shared by all the member : modifying a member will modify the other member as well. Here, you're first assigning 10 to member 'a' : inside the union, you have
0000 0000 0000 1010
Then, you're assigning 30 to member 'b' : the memory inside the union is :
0000 0000 0001 1110
Because the memory is shared, 'a' is 30 as well. That's why the output is 30.