Union, part 1
Union allows you to reuse a memory space for different-different data types, only one data can be stored at a time
Here is an example:
Try it here:
Output:
Let' break down this example:
We create a simple union with 2 data inside,
a
asinteger
andb
asdouble
.Once we store
a = 3
and print it, u1's memory addess will store 3 as a integer.Now when we set
b = 50
and print it, u1's memory address will store 50 as a double.And now if you try to read value of
a
, it will lose its value and will be overridden with byes of double (b).Here we reused same memory location as different data types.
Last updated