Govt. Exams
Entrance 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.
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.
Union is memory-efficient as members share space. Only one can be accessed at a time, which suits the requirement.
struct S { char c; int i; } s;
printf("%lu", sizeof(s));
char(1 byte) + padding(3 bytes) + int(4 bytes) = 8 bytes due to alignment requirements.
Bit fields save memory by storing multiple values in single bytes, but behavior varies by compiler/platform, and you cannot take addresses of bit field members.
An array of structures, where each structure contains a linked list (using self-referential pointers), is ideal for adjacency list representation.
A flexible array member must be the last member of a structure. This is a C99 feature used for dynamic-sized arrays.
#pragma pack(1) removes padding, making members occupy consecutive memory locations for compact storage.
struct X { int a; float b; };
struct Y { struct X x; int c; };
printf("%zu", sizeof(struct Y));
Nested struct X: int(4) + float(4) = 8 bytes. Y: struct X(8) + padding(0) + int(4) = 12, but with overall alignment it becomes 16 bytes.
Unions are optimal for memory-constrained scenarios and hardware programming where type casting is needed.