Summary - Unions and enums
- C course
- Intermediate
- Lesson 41/116
- 5 min
Combine union, enum and bit fields to write a state machine.
Summary - Unions and enums
In this summary you'll combine union, enum and bit field concepts to write a state machine. Throughout the group you learned union sharing, enum constants, the tagged union pattern, the typedef enum shortcut and bit field packing.
The state machine uses these parts: a State type with typedef enum, a struct Machine with State state and a unsigned running : 1 bit field. In a real app these parts become state transitions, event handling and flag management. C interpreters, compilers and hardware drivers start with this pattern.
Practice Write a state machine
Define typedef enum { IDLE, ACTIVE, STOPPED } State;. Define struct Machine with State state; and unsigned running : 1;. In main, write struct Machine m;; set m.state = ACTIVE; and m.running = 1;. Print with printf("%d %d\n", m.state, m.running);.
Starter code
#include <stdio.h>
// Define State with typedef enum (IDLE, ACTIVE, STOPPED)
// Define struct Machine (State state and running 1 bit)
// In main declare m, set state to ACTIVE, running to 1 and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
typedef enum { IDLE, ACTIVE, STOPPED } State;
struct Machine {
State state;
unsigned running : 1;
};
int main(void) {
struct Machine m;
m.state = ACTIVE;
m.running = 1;
printf("%d %d\n", m.state, m.running);
return 0;
}Expected output
1 1
Summary
In this group you learned union, enum, typedef enum and bit fields. You combined them to write a state machine.
A union shares memory, an enum gives named constants, a typedef provides short type names and bit fields pack data. These four tools are the foundation of data modeling in C: protocols, hardware registers and state machines build on them. In the next groups you'll write and read data to disk with file I/O; you'll improve safety with error handling. These foundations are the building blocks of real-world C projects.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which shares memory between members?
- struct
- enum
- union Correct answer
- typedef
Explanation: A union shares memory between members.
2 Match concepts to purpose
| Term | Meaning |
|---|---|
union |
Shared memory |
enum |
Named constants |
typedef |
Type alias |
bit field |
Bit packing |