Skip to study material
← Question index

QUESTION 18

Explain union types and contrast their storage with structures.

5 marks

Answer in brief

A union offers alternative representations within one shared storage area.

Declaration

union Value { int count; double price; };

Storage

The union must be large enough and suitably aligned for its members, possibly with padding. Unlike a structure, it does not reserve independent simultaneous storage for every member. Do not assume its size is exactly the largest member size without considering layout requirements.

Example

Assign v.count = 5 and use v.count. Later assign v.price = 12.5 and use v.price. The later write replaces the shared representation; count and price should not be treated as two independent values retained together.

Choosing the current member

A tagged union pairs a discriminator, often an enum, with a union. The tag records whether the current intended value is a count, price or another alternative. Every update must keep the tag and stored member consistent. The tag is separate data; C does not maintain it automatically.

Precaution

For clear introductory code, read the member corresponding to the stored alternative. Reading a different member reinterprets stored representation and can have implementation-dependent results or invalid representations. It is not a portable general-purpose numeric conversion; use a normal value conversion when converting int to double.

Complexity

Selecting a known member is O(1). A union can avoid allocating separate space for alternatives that are never needed simultaneously. The memory benefit depends on the actual member types and alignment.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
union Value { int count; double price; };

int main(void)
{
    union Value v;
    v.count = 5; printf("Count = %d\n", v.count);
    v.price = 12.5; printf("Price = %.1f\n", v.price);
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Count = 5
Price = 12.5