NBC 103 • Unit 416 min readHigh Exam Frequency

Unions vs Structures & Bit-Fields Memory Optimization

Unit 4: Structures, Unions, Enums & Storage ClassesProblem Solving Using C

👨‍🏫 Professor's Mental Model: The Private Apartment Suite vs Shared Single-Bed Room

Structure ek aisi building hai jisme har member ka apna alag personal bedroom hai: sab log ek saath apne kamre me reh sakte hain (Separate Memory). Lekin Union ek aisa hotel room hai jisme sirf EK HI BED hai: chahe int soye, float soye ya char soye—ek waqt me sirf ek hi mehmaan reh sakta hai! Naya mehmaan aate hi purana bahar fenk diya jata hai (Memory Overwritten)! Isliye Union ki total memory sirf uske sabse bade member ke barabar hoti hai!

Academic Lecture Notes & Solved Study Pages

Unit 4 • Core Concepts, Step-by-Step Proofs & Notebook Solutions

3 Notebook Pages
NOTEBOOK PAGE 1 OF 3

1. Union: Definition, Syntax & Shared Memory Principle

Definition: A user-defined data type similar to a structure, with one profound difference: all members share the exact same starting memory address in RAM!
Syntax:

union Record {

int i; // 4 Bytes

float f; // 4 Bytes

char ch; // 1 Byte

};

Size Calculation Rule:
- Size of struct = Sum of all member sizes (+ padding).
- Size of union = Size of the LARGEST member (e.g. `sizeof(union Record)` is strictly 4 Bytes!).
The Overwrite Phenomenon:

Only the most recently written member retains valid data. Mutating `r.f = 3.14f` corrupts whatever integer was previously stored in `r.i` because they occupy the exact same 4 bytes of silicon memory.

NOTEBOOK PAGE 2 OF 3

2. Real-World Applications of Unions

Embedded Systems & Hardware Registers: Interfacing with CPU registers that can be accessed as either a whole 32-bit word or four individual 8-bit bytes.
Variant Data Types: Storing different data types dynamically depending on status (e.g. integer error code OR pointer string).
Memory Conservation: Saving RAM on memory-constrained microcontrollers when multiple attributes are mutually exclusive.
NOTEBOOK PAGE 3 OF 3

3. Bit-Fields: Compacting Boolean Flags to Single Bits

In C, the smallest primitive type (`char`) occupies 8 bits. If you only need to store a 1-bit boolean flag (0 or 1), 7 bits are wasted!

Bit-Fields allow exact specification of bit-widths inside structures:

struct DeviceStatus {

unsigned int is_ready : 1; // Consumes exactly 1 bit

unsigned int error_code : 3; // Consumes 3 bits (values 0 to 7)

unsigned int mode : 2; // Consumes 2 bits (values 0 to 3)

};

Total size: Packs all 3 attributes into a single 4-byte unsigned int word, saving massive amounts of memory in networking packets and OS kernels.
Master 6-Parameter Comparison: Structure (struct) vs Union (union)
ParameterStructure (struct)Union (union)
Keywordstructunion
Memory AllocationSeparate memory space allocated for every individual memberShared common memory space for all members
Total Byte SizeGreater than or equal to sum of all member sizesEqual to the size of its single largest member (+ alignment)
Member CoexistenceAll members can hold valid, active data simultaneouslyOnly ONE member can hold valid, active data at any instant
Alteration Side-EffectModifying one member has ZERO effect on othersModifying one member corrupts/overwrites previous member data
Member Memory AddressEach member has a distinct, increasing memory addressAll members share the EXACT same base memory address

Interactive Tested Code Example

#include <stdio.h>

union DataPacket {
    int integer_val;
    float float_val;
    char char_val;
};

int main(void) {
    union DataPacket packet;

    printf("=== UNION SHARED MEMORY ARCHITECTURE ===\n");
    printf("sizeof(packet): %zu Bytes (Size of largest member: float/int)\n\n", sizeof(packet));

    // 1. Assigning Integer
    packet.integer_val = 100;
    printf("Assigned packet.integer_val = 100\n");
    printf("Integer: %d | Float (Corrupt): %f\n\n", packet.integer_val, packet.float_val);

    // 2. Assigning Float (Overwrites Integer!)
    packet.float_val = 98.75f;
    printf("Assigned packet.float_val = 98.75\n");
    printf("Float:   %.2f | Integer (Corrupted bits): %d\n", packet.float_val, packet.integer_val);
    return 0;
}
💡 Note:Demonstrates Union shared memory behavior: assigning to float_val overwrites the underlying memory bits, corrupting integer_val.

🎯 University Exam Scoring Blueprint

  • In university exams, Structure vs Union is a perennial 10-mark question; always reproduce the 6-parameter table.
  • Draw memory boxes contrasting separate contiguous slots (struct) with a single overlapping box (union).
  • Mention that address-of operator (&) cannot be used on bit-field members because memory addresses are byte-aligned, not bit-aligned.

Top Viva Questions on Unions vs Structures & Bit-Fields Memory Optimization

2 Questions
1

Can we use the address-of operator (&) on a bit-field member?

2

What is the memory address of the first member of a union compared to the union variable itself?