0
How does this code work ?
I was given this question in a C challenge. I'm not able to understand the output/ working. Ques: What is the output of this code ? Union values{ int first; int second; char third[1]; }; int main(){ union values v; v.first=0; v.third[0]='b'; printf("%d\n",v.second); return 0; } Answer: 98 In case this has already been answered, please direct me to the post I'm not able to locate it .
9 Antworten
+ 5
What's a union?
"In computer science, a union is a value that may have any of several representations or formats within the same position in memory [...] ¹"
that means v.first=0; sets all three members of `values` to zero (so do v.third[0] = 'b' sets all of them to `b` or ASCII value 98) like so
union values v;
v.first=0;
printf("%d %d %d\n", v.first, v.second, v.third[0]); // 0 0 0
v.third[0]='b';
printf("%d %d %d\n", v.first, v.second, v.third[0]); // 98 98 98
___
¹ https://en.wikipedia.org/wiki/Union_type
+ 1
Variables stored in union are sharing single memory location, if 1 variable change, the value in memory region are change and so the others because they're share single memory location.
+ 1
C++ Soldier (Babak) Thank you
0
Roneel Why are we printing the ASCII value of b ? I'm still confused .
0
Taste so the last value stored is of v.third which is 'b' and when we print second it prints the ASCII value of b ?
0
Yes
0
union values {
int i_val;
float f_val;
char c_val;
};
union values val;
val.c_val = 'a';
- 1
Taste Thank you very much :).