Entrance Exams
Govt. Exams
Unions are preferred when you have mutually exclusive data (only one member is used at a time) and memory is critical. A classic example is storing different data types in a tagged union pattern used in compilers and interpreters.
Passing a pointer to the structure avoids copying the entire structure in memory, which is especially important for large structures with array members. This improves performance significantly.
Members do not need to be explicitly initialized. Uninitialized members in automatic structures have indeterminate values, while static structures have zero-initialized members. Designated initializers (C99+) allow flexible initialization order.
A self-referential structure contains a pointer to its own type. This is the fundamental building block for creating linked lists, trees, and other dynamic data structures.
The maximum number of bits for a bit field member cannot exceed the size of the underlying type. For int (typically 32 bits), you can allocate up to 32 bits to a single member.
union Test {
int a;
char b;
};
union Test t;
t.a = 65;
printf("%d %c", t.a, t.b);
Since union members share memory, the output depends on the system's endianness. On little-endian systems, t.b would be 65 (or 'A'), but on big-endian systems, the result differs.
Anonymous structures allow defining structures without a tag name directly inside another structure, making members accessible as if they belong to the outer structure.
struct Data {
int x;
char y;
double z;
};
Assuming int=4 bytes, char=1 byte, double=8 bytes, what is the size of struct Data due to padding?
Memory alignment causes padding. x(4) + padding(4) + y(1) + padding(7) + z(8) = 24 bytes. The compiler aligns to the largest member (double = 8 bytes).
In structures, memory is allocated for each member independently. In unions, all members share the same memory location, so total memory allocated equals the size of the largest member.
Union is memory-efficient as members share space. Only one can be accessed at a time, which suits the requirement.