icp/oer/courses/c-basics/sections/12-struct_enum/05-unions/content.html

18 lines
987 B
HTML

<p>
The last construct to lay out your data are unions. Unions are used to <b>store different types in the same memory location</b>.
This has three main practical reasons:
<ol>
<li>Naming the same data differently.</br>
Lets say you want a 3d vector, which you can use both as position and as color. You can use a union to define it as x,y,z and r,g,b.</li>
<li>Storing different data in the same location.</br>
To do that, you use the union to declare which types you want to store and and enum to store, which type actually got stored.</li>
<li>Accessing the same data in a different way.</br>
If you are doing low level programming, you sometimes have to deal with the byte order of different platforms.
It could then be useful to access types in form of bytes.
</li>
</ol>
</p>
<p>
Your task is to define the struct box, which holds either an int or an float in the same position and tells you with an enum what it has stored.
</p>