What is the output of this code??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

What is the output of this code???

https://www.sololearn.com/post/262217/?ref=app

10th Mar 2020, 4:46 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
3 Answers
+ 4
Well, let's make this "Why is the output of this code?". The C standard actually clearly defines this case (yes, once in a while, something is not Undefined Behaviour in C). When an attempt is made to read an inactive member of a union, the appropriate part of the object representation of the value is reinterpreted as the type of the accessed member. This process is known as "type-punning" and only a thing in C, but not C++. So, since "ch" is already conveniently the same size as 'i', it is reinterpreted as short int. The SoloLearn environment is a little-endian one, meaning the most significant byte is actually on the right, as opposed to a big-endian system. "ch" is stored in binary as 00000011 and 00000010, but since the right byte is the most significant one, the resulting combined integer would look like this in binary represantation (from left to right) 0000001000000011 which in the end equals 515 as the last number in the output.
10th Mar 2020, 5:19 PM
Shadow
Shadow - avatar
+ 6
You can also check on Sololearn Playground.
10th Mar 2020, 4:49 PM
A͢J
A͢J - avatar
+ 2
Waaoo i got it and thanku veryyyy much
10th Mar 2020, 5:22 PM
A S Raghuvanshi
A S Raghuvanshi - avatar