+ 1

Though i havent assigned any value to" v. second " it prints 97. How?

https://code.sololearn.com/cEc6qV0QavW9/?ref=app

10th Oct 2019, 1:18 PM
Joѕнυα
Joѕнυα - avatar
3 Antworten
+ 5
A union has only one memory location reserved for all its members. Setting one variable will affect all others. In this case you set the union to 'a' which is 97 in ASCII. Therefore it prints 97 when you access the union through a integer member. And btw. char[0] is basically wrong because you create an array with 0 elements. C is pretty tolerant (and that's why this code even works) and so weird bugs and interactions might occur. Actually the element char[0] doesn't even exist but C doesn't check for array bounds so you can access it anyway (though you obviously shouldn't)
10th Oct 2019, 1:30 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
This is due to You can define a union with many members, but only one member can contain a value at any given time. So the instruction "printf ("% d ", v. Second);" must go after the second sea value declared. That is why when printing you print 97 because it is the value of the letter "a".
10th Oct 2019, 1:36 PM
Stiven 98
Stiven 98 - avatar
10th Oct 2019, 1:38 PM
Stiven 98
Stiven 98 - avatar