Skip to study material
← Question index

QUESTION 20

Compare structure and union types with suitable uses.

5 marks

Answer in brief

Structures model a group of values needed together. Unions model alternative values sharing storage.

Structure

A Student record can need roll, name and marks at the same time. Its members occupy distinct parts of the record, although padding may occur between or after them. Assigning one ordinary member does not overwrite an unrelated member.

Union

A Value union may hold a count or price alternative. The members overlap, so storing the price changes the shared representation that was used for count. Use a suitable tag to remember which alternative the program intends to read.

Shared features

Both are user-defined types with named members accessed using . on an object or -> through a suitable pointer. Both can be nested in other aggregates and used in function interfaces. Neither is an automatic mechanism for text input validation, target allocation or pointer ownership.

Size comparison

The structure size includes the storage needed for all members plus permitted padding. The union size is enough for its alternatives and alignment. Do not write a universal formula that ignores padding or assumes identical numeric sizes on every system.

Choosing a representation

Use a structure for a complete employee record. Use a tagged union for a token whose payload is one of several kinds. A structure containing an enum tag and a union payload combines both ideas. Fixed member access takes O(1); processing a variable-length pointed-to payload has its own cost.

Reference table

↔ Scroll horizontally on a small screen
Structure and union
FeatureStructureUnion
Member storageSeparateOverlapping
Typical valuesNeeded togetherAlternative payloads
SizeMembers plus permitted paddingEnough for alternatives and alignment
UseStudent recordTagged alternative value