QUESTION 17
What is a union?
2 marksAnswer
A union is a type whose members share overlapping storage. It is normally used to hold one selected member value at a time.
QUESTION 17
A union is a type whose members share overlapping storage. It is normally used to hold one selected member value at a time.
QUESTION 18
A union offers alternative representations within one shared storage area.
union Value { int count; double price; };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.
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.
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.
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.
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.
/* 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;
}The example uses values in the code.
Count = 5
Price = 12.5