Project 5: Control Flow Pattern Library

A collection of control flow idioms including finite state machines, structured error handling, and safe loop patterns.

Quick Reference

Attribute Value
Primary Language C
Alternative Languages None
Difficulty Level 1 - Beginner
Time Estimate See main guide
Knowledge Area Programming Fundamentals, Idioms
Tooling GCC, Godbolt
Prerequisites See main guide

What You Will Build

A collection of control flow idioms including finite state machines, structured error handling, and safe loop patterns.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Structured error handling → Maps to goto-based cleanup patterns
  • Switch statement best practices → Maps to avoiding fallthrough bugs
  • Loop invariant design → Maps to provably correct code

Key Concepts

  • Map the project to core concepts before you code.

Real-World Outcome

# 1. Error handling demonstration
$ ./control_flow error_handling
Opening resource A... OK
Opening resource B... OK
Opening resource C... FAILED

Cleanup sequence:
  Closing resource B (was opened)
  Closing resource A (was opened)
  NOT closing resource C (was not opened)
Function returned: -1 (RESOURCE_C_FAILED)

# 2. State machine
$ ./control_flow fsm "aabba"
Input: aabba
STATE: START -> (a) -> A_SEEN
STATE: A_SEEN -> (a) -> A_SEEN
STATE: A_SEEN -> (b) -> B_SEEN
STATE: B_SEEN -> (b) -> B_SEEN
STATE: B_SEEN -> (a) -> A_AFTER_B
Final: ACCEPTED (ends in A_AFTER_B)

$ ./control_flow fsm "aabb"
Input: aabb
...
Final: REJECTED (ends in B_SEEN)

# 3. Loop patterns
$ ./control_flow loops
Sentinel loop: Read 5 numbers until -1 entered
For loop: Processed 10 items
Early exit: Found target at index 3
While-true-break: Validated input after 2 retries

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: PROFESSIONAL_C_PROGRAMMING_MASTERY.md
  • Effective C, 2nd Edition by Robert C. Seacord