+ 2

Can you explain the process of this code.(i thought that answer would be [ X, 65 ] but real answer i get as a output [A, 65] ).

#include <iostream> using namespace std; union mytype{ char c; unsigned int i; } u; int main(){ u.c='X'; u.i=65; cout <<u.c<<" "<<u.i; return 0; }

17th Jan 2021, 2:22 PM
Shivam Godbole
Shivam Godbole - avatar
1 Antwort
+ 1
A union shares the same memory for all its members. If you change c, then you change i. Likewise, if you change i, then you might also change c (depending on which byte of i that you change). Be certain to understand that the data types are different sizes. So c overlaps the same memory with i only on the first byte of i. Also beware that on another type of computer and another compiler they might overlap on the high byte of i or a middle byte (big-endian versus little-endian, different integer size).
17th Jan 2021, 4:08 PM
Brian
Brian - avatar