Structures, Unions & Enums in C
Create custom composite types using struct, optimize memory with unions, implement type aliases with typedef, and define enum constants.
- A
structgroups variables of different data types together under a single user-defined type name. - Struct members are accessed using dot notation (
student.id) or arrow notation (ptr->id). - A
unionshares a single memory location among all its members; its size equals its largest member. typedefcreates convenient shorthand aliases for complex types.enumdefines a set of named integer constants for readable state handling.
Defining and Using Structures
While arrays hold homogeneous data where all elements must be of the same type, structures allow you to group heterogeneous attributes of different data types (such as a Student having an ID, Name, and GPA) under a single cohesive entity.
Each variable inside a structure is called a member or field. Using typedef provides a clean type alias so you can declare variables without repeatedly prefixing with the struct keyword.
Structures vs. Unions: The Memory Difference
Understanding how structures and unions allocate memory in RAM is a core systems programming concept:
In a struct, each member receives its own distinct memory offset. In a union, all members share the exact same starting memory address, which allows significant memory savings in resource-constrained embedded systems when only one attribute is active at a time.
| Feature / Metric | Structure (`struct`) | Union (`union`) |
|---|---|---|
| Memory Allocation | Sum of all member sizes (+ compiler padding bytes) | Size of the largest member only |
| Member Access | All members can be stored and accessed simultaneously | Only one member can be actively held at any given moment |
| Primary Use Case | Complex entities with multiple active attributes (e.g. Student, Packet) | Mutually exclusive data variants (e.g. dynamic JSON values, raw register overlays) |
| Keyword | `struct` | `union` |
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
When accessing a struct member through a pointer (e.g. Student *s), which operator is used?
Beginner