How does this code work ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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 .

12th Nov 2018, 1:00 PM
Sreyashi Bhattacharjee
9 Answers
+ 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
12th Nov 2018, 1:30 PM
Babak
Babak - avatar
+ 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.
12th Nov 2018, 1:20 PM
Taste
Taste - avatar
+ 1
12th Nov 2018, 1:31 PM
Sreyashi Bhattacharjee
12th Nov 2018, 1:05 PM
Roneel
Roneel - avatar
0
Roneel Why are we printing the ASCII value of b ? I'm still confused .
12th Nov 2018, 1:09 PM
Sreyashi Bhattacharjee
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 ?
12th Nov 2018, 1:25 PM
Sreyashi Bhattacharjee
0
Yes
12th Nov 2018, 1:25 PM
Taste
Taste - avatar
0
union values { int i_val; float f_val; char c_val; }; union values val; val.c_val = 'a';
19th Oct 2021, 2:26 PM
Shilpa L
- 1
Taste Thank you very much :).
12th Nov 2018, 1:26 PM
Sreyashi Bhattacharjee