Unions Flashcards

1
Q

What is a union?

A
  • 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you code a union?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do struct and Union differ in memory? Draw it.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How are unions accessed?

Example for members i and d.

How would changing i affect d?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How would you use unions to save space with the following structure?

How would you access a book’s title in the union?

A

If c is a catalog_item, we can print a book’s title with :

printf(“%s”, c.item.book.title);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

In general, how can you tell which member of a union was last changed and therefore contains a meaningful value?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How would you code a tag field for a union?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the code for a function that prints the correct number in a stuct based on it’s kind?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly