Unions Flashcards
What is a union?
- Like a struct, contains one or more members, possibly of different types.
- The compiler allocates only enough space for the largest of the members, which overlay each other in this space
- Assigning a new value alters the values of the members as well
How do you code a union?
How do struct and Union differ in memory? Draw it.
How are unions accessed?
Example for members i and d.
How would changing i affect d?
How would you use unions to save space with the following structure?
How would you access a book’s title in the union?
If c is a catalog_item, we can print a book’s title with :
printf(“%s”, c.item.book.title);
If we needed an array whose elements are a mixture of int and double values, how would we define the code for this union and array?
In general, how can you tell which member of a union was last changed and therefore contains a meaningful value?
How would you code a tag field for a union?
After the pictured code, each time we assign a value to a member of u, we’ll also change kind to remind us which member of u we modified.
Example:
n. kind = INT_KIND;
n. u.i = 82;
n is assumed to be a Number variable
What is the code for a function that prints the correct number in a stuct based on it’s kind?