QUESTION 19
State one storage difference between a structure and a union.
2 marksAnswer
A structure has separate member storage so all members can hold values together. Union members overlap and represent alternatives.
QUESTION 19
A structure has separate member storage so all members can hold values together. Union members overlap and represent alternatives.
QUESTION 20
Structures model a group of values needed together. Unions model alternative values sharing storage.
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.
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.
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.
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.
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.
| Feature | Structure | Union |
|---|---|---|
| Member storage | Separate | Overlapping |
| Typical values | Needed together | Alternative payloads |
| Size | Members plus permitted padding | Enough for alternatives and alignment |
| Use | Student record | Tagged alternative value |