In competitive programming for GATE/ISRO 2025, which scenario would union be preferable over structure?
AWhen you need to store multiple data types independently
BWhen memory optimization is critical and you need mutually exclusive data
CWhen creating complex data structures like trees
DWhen implementing object-oriented features
Correct Answer:
B. When memory optimization is critical and you need mutually exclusive data
EXPLANATION
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.
What will be the output of the following code?
union Test {
int a;
char b;
};
union Test t;
t.a = 65;
printf("%d %c", t.a, t.b);
A65 A
B65 65
C0 A
DDepends on endianness
Correct Answer:
D. Depends on endianness
EXPLANATION
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.
In competitive programming, when you need a structure that can hold either an integer or a floating-point number (but not both simultaneously) in the most memory-efficient way, which should you use?
Astruct with both members
Bunion with both members
CAn array of size 2
DA single variable with type casting
Correct Answer:
B. union with both members
EXPLANATION
Union is memory-efficient as members share space. Only one can be accessed at a time, which suits the requirement.
If you have a structure with bit fields, which statement about their behavior is true?
ABit fields can improve memory efficiency for small values
BBit fields guarantee portability across all platforms
CBit fields allow taking addresses (&) of members
DBit fields support all data types
Correct Answer:
A. Bit fields can improve memory efficiency for small values
EXPLANATION
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.