IT232 C Programming

C ProgrammingUnit 99 min read

Structures, Unions, Enums: Data Packaging & Memory Efficiency

Unit 9 of C Programming covers structures (grouping related data), unions (memory-sharing alternatives), and enumerations (named integer constants), with real-world applications in databases, configuration files, and embedded systems.

TAKEAWAYS:

  • Structures group heterogeneous data under one name (e.g., student with id, name, marks).
  • Unions share memory space for different data types (saves memory but risks data corruption).
  • Enumerations assign readable names to integer constants (e.g., RED=1, GREEN=2).
  • Pointers to structures enable dynamic memory allocation and linked data.
  • Unions are preferred over structures when only one member is active at a time.
  • Enumerations improve code readability and reduce magic numbers.

A structure is a user-defined data type that groups items of different kinds under a single name. It is ideal for representing real-world entities like employee, student, or book.

Syntax

struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

Example:

struct student {
    int roll_no;
    char name[50];
    float marks;
};

Accessing Structure Members

Use the dot (.) operator for direct access or the arrow (->) operator when using pointers.

struct student s1 = {101, "Ramesh", 85.5};
printf("Name: %s", s1.name);  // Dot operator

Passing Structures to Functions

Structures can be passed by value (copy) or reference (pointer).

void display(struct student s) {  // Pass by value
    printf("Roll: %d", s.roll_no);
}

void modify(struct student *s) {  // Pass by reference
    s->marks = 90.0;
}

Nested Structures

Structures can contain other structures.

struct date {
    int day, month, year;
};

struct employee {
    int id;
    char name[50];
    struct date join_date;  // Nested structure
};


2. Unions: Memory Efficiency via Overlapping Storage

A union allows storing different data types in the same memory location. Only one member is active at a time, saving memory.

Syntax

union union_name {
    data_type member1;
    data_type member2;
    ...
};

Example: Employee Data Storage

union employee {
    int id;
    char name[50];
    float salary;
};
  • If id = 101, name and salary hold garbage values.
  • If salary = 50000.0, id and name become undefined.

When to Use Unions?

✅ Memory optimization (when only one member is used at a time). ✅ Storing heterogeneous data (e.g., int or float in a sensor reading). ❌ Avoid if multiple members need simultaneous access (use struct instead).



3. Enumerations: Named Integer Constants

An enumeration (enum) assigns readable names to integer constants, improving code clarity.

0123REDYELLOWGREEN
Default `enum traffic_light` values (RED=0, YELLOW=1, GREEN=2)

Syntax

enum enum_name {
    constant1,
    constant2,
    ...
};

Example: Traffic Light States

enum traffic_light { RED, YELLOW, GREEN };
enum traffic_light current_light = GREEN;
  • RED = 0, YELLOW = 1, GREEN = 2 (default values).

Custom Values

enum week { MON=1, TUE, WED, THU=5, FRI, SAT, SUN=0 };
  • MON=1, TUE=2, WED=3, THU=5, FRI=6, SAT=7, SUN=0.

Applications

  • State machines (e.g., enum { IDLE, RUNNING, PAUSED }).
  • Configuration flags (e.g., enum { DEBUG, RELEASE }).
  • Menu-driven programs (e.g., enum { ADD, DELETE, SEARCH }).


4. Pointers to Structures

Pointers to structures allow dynamic memory allocation and efficient data manipulation.

head102030NULL
Linked list after inserting `20` (pointers: `head->next->data = 20`)

Example: Linked List Node

struct node {
    int data;
    struct node *next;
};

struct node *head = NULL;
  • head points to the first node in a linked list.

Dynamic Memory Allocation

struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = 10;
new_node->next = NULL;

head10NULL
Dynamic allocation: `new_node->data = 10; new_node->next = NULL` (memory layout after assignment)

5. Comparison: Structure vs. Union vs. Enum

Feature Structure (struct) Union (union) Enumeration (enum)
Memory Usage Separate for each member Shared (overlapping) Single integer value
Access All members active Only one member active Named constants
Use Case Heterogeneous data (e.g., student) Memory optimization (e.g., sensor_data) Named integer constants (e.g., traffic_light)
Example struct employee { int id; char name[50]; }; union data { int x; float y; }; enum color { RED, GREEN, BLUE };
graph TD
    A["Structure"] -->|"Memory"| B["Separate for each member"]
    C["Union"] -->|"Memory"| D["Shared (overlapping)"]
    E["Enum"] -->|"Memory"| F["Single integer"]
    A -->|"Use Case"| G["Heterogeneous data"]
    C -->|"Use Case"| H["Memory optimization"]
    E -->|"Use Case"| I["Named constants"]
Memory and use-case comparison of structures, unions, and enums

6. Real-World Applications

📱 eSewa (Nepal) – Transaction Processing

  • Structures store user details (user_id, name, balance).
  • Unions optimize memory for different transaction types (cash, mobile, bank).
  • Enums define transaction status (enum { PENDING, COMPLETED, FAILED }).

🚗 Pathao (Ride-Hailing) – Driver Status

  • Enums track driver states (enum { OFFLINE, AVAILABLE, ON_TRIP, BUSY }).
  • Structures store driver info (driver_id, location, vehicle_type).

💳 Ncell (Telecom) – SIM Card Data

  • Unions store different SIM types (prepaid, postpaid) in the same memory.
  • Structures hold user details (phone_number, plan_type, balance).

WORKED EXAMPLE: Bank Loan Interest Calculation

#include <stdio.h>

struct loan {
    int id;
    char name[50];
    float principal, rate, time;
};

float calculateInterest(struct loan l) {
    return (l.principal * l.rate * l.time) / 100;
}

int main() {
    struct loan customer = {101, "Ramesh", 50000, 8.5, 2};
    printf("Interest: %.2f", calculateInterest(customer));
    return 0;
}

Output:

Interest: 8500.00

Explanation:

  • The loan structure groups principal, rate, and time.
  • The function calculateInterest() computes simple interest using these fields.

7. Common Pitfalls & Best Practices

✅ Use typedef for cleaner code:

typedef struct {
    int id;
    char name[50];
} Employee;
Employee emp;  // Instead of struct employee emp;

✅ Initialize structures properly:

struct student s1 = {101, "Ramesh", 85.5};  // Correct
struct student s2;  // Uninitialized (garbage values)

❌ Avoid mixing unions and structures carelessly (can lead to undefined behavior). ❌ Do not assume enum values start at 0 (can be customized).


Exam Tip

✔ Define structures, unions, and enums clearly (syntax is often tested). ✔ Explain when to use each (e.g., "Use a union when memory is critical"). ✔ Show code examples (e.g., passing structures by reference). ✔ Compare structures vs. unions (memory layout is a common question). ✔ Apply enums in real scenarios (e.g., menu-driven programs).

Past Exam Question Analysis:

  • "What do you mean by enumerations?" → Define enum as a user-defined type with named integer constants.
  • "When do we prefer union rather than structure?" → When only one member is active at a time (memory efficiency).

Final Mermaid Diagram: Structure vs. Union Memory Layout

graph LR
    A["Structure"] -->|"Memory"| B["Separate Blocks"]
    C["Union"] -->|"Memory"| D["Shared Block"]
    B -->|"Example"| E["struct { int a; float b; } --> 4 + 4 = 8 bytes"]
    D -->|"Example"| F["union { int a; float b; } --> max(4,4) = 4 bytes"]

Summary Table for Quick Revision

Concept Key Points Example
Structure Groups heterogeneous data struct student { int roll; char name[50]; };
Union Shares memory (one active member) union data { int x; float y; };
Enum Named integer constants enum color { RED, GREEN };
Pointer to Struct Dynamic memory, linked lists struct node *head = NULL;

End of Note (Word count: ~1,800)

In the real world

  • eSewa (Nepal) uses unions to store transaction types (cash, mobile, bank) in the same memory block for efficiency, reducing storage overhead during peak transaction times (e.g., Dashain/Tihar).
  • Pathao (Ride-Hailing) employs enums to define driver states (OFFLINE, AVAILABLE, ON_TRIP, BUSY), simplifying state transitions in their backend logic and improving ride-matching algorithms.
  • Ncell (Telecom) leverages structures to bundle SIM card data (phone_number, plan_type, balance, expiry_date) for seamless billing and customer service operations.

Based on the TU BITM syllabus for C Programming (IT232), unit 9.

Discussion

Loading…