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] ). | SoloLearn: Learn to code for FREE!

+1

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; }

c++ c

1/17/2021 2:22:15 PM

Lina Godbole

1 Answer

New Answer

+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).