C++ Union

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/15

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

16 Terms

1
New cards

What are unions for?

To define a type with multiple fields and each field occupies the same space in memory so that if you overwrite one of them in memory, they are all overwritten.

2
New cards

How much storage is allocated for a union?

The size of the largest field.

3
New cards

True or False: You can safely initialize all members of a union in-class in C++11.

False. Only the first member can have a default in-class initializer.

4
New cards

What is the output of the following code?
union U { int x; double y; };

U u;

u.x = 5;

std::cout << u.x;

5x is the active member and holds the value 5.

5
New cards

What happens if you read a different member of a union than the one most recently written?

The behavior is undefined; the value will likely be a reinterpretation of the shared memory.

6
New cards

Provide a use case where unions are particularly useful.

Memory-efficient storage of mutually exclusive data types, hardware register mapping, or type punning in low-level programming.

7
New cards

What will this output?

union U { int x; float y; };

U u;

u.y = 3.5f;

std::cout << u.x;

Undefined/garbled integer value; x interprets the first 4 bytes of the float y.

8
New cards

Can unions contain non-POD (non-Plain Old Data) types in modern C++?

Yes, since C++11, but only if they have trivial constructors, destructors, and copy/move operations.

9
New cards

How would you safely track which member of a union is active?

Use a separate enum or a std::variant (safer modern alternative).

10
New cards

True or False: All union members share the same memory location.

True. This is the defining feature of a union.

11
New cards

Why is understanding memory layout important?

Some CPUs require data to start at certain byte boundaries. Certain things like packets, IO, network interactions have bytes mapped to certain operations. Too much memory can cause things to be misallocated.

12
New cards

Why might something like this actually be 8 bytes?
struct S {

char a; // 1 byte

int b; // 4 bytes

};

Memory layout might actually be 8 bytes due to padding to align b to a 4-byte boundary. This is in order to meet a boundary and ensure that any following data is after the boundary.

13
New cards

What does Endian mean

order in which bytes of a multi-byte number are stored in memory

14
New cards

What does little-endian mean

least significant byte is stored firstW

15
New cards

What does big endian mean

Most significant byte is stored first

16
New cards