C ProgrammingUnit 96 min read
Structures, Unions, Enums: Organizing Data in C
Unit 9 of C Programming covers structures (custom data types combining variables), unions (memory-sharing alternatives), and enumerations (named integer constants). Learn how to define, access, and use them, with real-world examples from banking, e-commerce, and traffic systems.
What Are Structures?
A structure (struct) is a user-defined data type that groups related variables of different types under a single name. Unlike arrays (which hold identical data types), structures can hold mixed data types.
Why Use Structures?
- Logical grouping: Combine related data (e.g., a
studentwithname,roll_no, andmarks). - Memory efficiency: Access all fields with a single variable name (e.g.,
student1.name). - Passing to functions: Treat the entire structure as one unit.
Syntax
struct structure_name {
data_type member1;
data_type member2;
// ...
};
Example: Define a student structure.
struct student {
char name[50];
int roll_no;
float marks;
};
Accessing Structure Members
Use the dot (.) operator for direct access:
struct student s1;
strcpy(s1.name, "Ramesh");
s1.roll_no = 101;
s1.marks = 85.5;
Passing Structures to Functions
Pass by value (copy) or address (pointer) for efficiency.
void display(struct student s) {
printf("Name: %s, Roll: %d, Marks: %.2f\n", s.name, s.roll_no, s.marks);
}
Real-World Example: Bank Account Management
ATM terminal handling account data as structures (Image: Alan Tennyson, CC BY-SA 4.0, via Wikimedia Commons)
Banks use structures to store customer records (e.g., account_holder with name, account_number, balance). When you check your balance via eSewa or Ncell Money, the system retrieves and displays this structured data.
Example Code:
struct account {
char name[50];
int acc_no;
float balance;
};
int main() {
struct account user1 = {"Hari Prasad", 12345, 5000.0};
printf("Account Holder: %s\nBalance: %.2f\n", user1.name, user1.balance);
return 0;
}
Output:
Account Holder: Hari Prasad
Balance: 5000.00
Nested Structures
Structures can contain other structures (e.g., a department inside a student).
struct department {
char dept_name[30];
int dept_code;
};
struct student {
char name[50];
struct department dept; // Nested structure
};
Arrays of Structures
Store multiple records (e.g., 100 students) in an array of structures.
struct student class[100];
class[0].roll_no = 1; // First student's roll number
Typedef for Simplicity
Use typedef to avoid repeating struct:
typedef struct {
char name[50];
int roll_no;
} Student; // Now use as `Student s1;`
What Are Unions?
A union shares memory among its members—only one member can hold a value at a time. Useful for memory optimization (e.g., storing different data types in the same space).
Syntax
union union_name {
data_type member1;
data_type member2;
// ...
};
Example: Storing Different Data Types
union data {
int i;
float f;
char str[20];
};
union data var;
var.i = 10; // Only `i` holds value; `f` and `str` are undefined
printf("%d\n", var.i); // Output: 10
Real-World Example: Network Packets
In NTC’s internet routing, packets may contain different data types (e.g., IP address as int or char). Unions allow efficient storage by reusing memory.
Unions vs. Structures
| Feature | Structure (struct) |
Union (union) |
|---|---|---|
| Memory Usage | Separate memory for each member | Shared memory (overlapping) |
| Access | All members can be accessed simultaneously | Only one member holds value at a time |
| Use Case | Logical grouping (e.g., student) |
Memory optimization (e.g., network packets) |
What Are Enumerations?
An enumeration (enum) defines named integer constants for readability.
enum day {MON, TUE, WED, THU, FRI, SAT, SUN};
enum day today = WED; // today = 2 (since MON=0)
Example: Traffic Light System
Red, Yellow, Green as enum constants (Image: Dietmar Rabich, CC BY-SA 4.0, via Wikimedia Commons)
enum traffic_light {RED, YELLOW, GREEN};
enum traffic_light light = GREEN; // light = 2
Real-World Example: Daraz Order Status
Daraz uses enums for order status (PENDING, SHIPPED, DELIVERED) to simplify code and avoid magic numbers.
Exam Tip
- Define structures/unions/enums correctly—syntax is critical.
- Practice accessing members (dot/arrow operators).
- Compare unions vs. structures—examiners test memory usage differences.
- Use typedef to simplify declarations (common in exams).
- Apply to real scenarios (e.g., bank records, traffic systems).
Worked Example: Student Database
Task: Store 3 students and print their details.
#include <stdio.h>
#include <string.h>
struct student {
char name[50];
int roll_no;
float marks;
};
int main() {
struct student class[3] = {
{"Ramesh", 101, 85.5},
{"Sita", 102, 90.0},
{"Hari", 103, 78.5}
};
for (int i = 0; i < 3; i++) {
printf("Name: %s, Roll: %d, Marks: %.2f\n",
class[i].name, class[i].roll_no, class[i].marks);
}
return 0;
}
Output:
Name: Ramesh, Roll: 101, Marks: 85.50
Name: Sita, Roll: 102, Marks: 90.00
Name: Hari, Roll: 103, Marks: 78.50
In the Real World
- eSewa/Khalti: Uses structures to store user profiles (
name,phone,balance) and transactions (amount,timestamp,status). - Pathao/Daraz: Enums for order status (
PENDING,ACCEPTED,DELIVERED) simplify logic in delivery tracking. - NEPSE Stock Exchange: Structures hold stock data (
symbol,price,volume), while unions optimize memory for different data types (e.g.,priceasfloatorint).
classDiagram
class Student {
+char name[50]
+int roll_no
+float marks
}
class Department {
+char dept_name[30]
+int dept_code
}
Student "1" --> "1" Department : contains
note for Student "Logical grouping of student data"
note for Department "Nested structure for department info"Based on the TU BIM syllabus for C Programming (IT232), unit 9.
Discussion
Loading…