Skip to content

State machine diagrams

Difficulty: Intermediate

Key concepts

  • state machine
  • state
  • event
  • transition
  • guard
  • action
  • final state
  • state/event table
  • impossible state
  • The parts of a state machine: states, events, transitions, guards, and actions.
  • How to check a state diagram for missing transitions, using a table of every state against every event.
  • Why an enum of states prevents impossible states that a set of bool flags allows.
  • How to translate a state diagram into C++: an enum class and one switch per event.

Some objects behave differently depending on what has happened to them. A loan can be renewed while it is on loan, but not once it is overdue. A returned loan accepts nothing more. The multiplicity lesson met this with an order that moved from draft to placed to shipped.

When the rules start with “while it is…” or “once it has…”, the object has a lifecycle, and a state machine describes it precisely:

Part Meaning In the loan example
State a situation the object is in, which decides how it reacts on loan, overdue, lost, returned
Event something that happens to the object renew, end of day, report lost, give back
Transition a move from one state to another, caused by an event on loan → overdue, at the end of a late day
Guard a condition that must be true for the transition “fewer than 2 renewals so far”
Action what the object does as part of the transition “one more renewal; due day 14 days later”
Final state a state with no transitions out, drawn with an arrow to the end marker [*] returned

The diagram writes a transition as event [guard] / action. Each part after the event is optional.

A loan starts on loan, with a due day. While on loan, it can be renewed up to twice; each renewal moves the due day 14 days later. At the end of each day, a loan on loan whose due day has passed becomes overdue. Overdue loans cannot be renewed. A loan on loan or overdue can be reported lost. A loan that is not yet returned can be given back, even if it was lost; it is then returned, and fined 20 cents for each day after the due day.

The loan's states, with each transition's event, guard, and action
Text description of the diagram

A loan is created on loan, with a due day. While on loan, renew keeps it on loan if it has had fewer than 2 renewals, counts one more renewal, and moves the due day 14 days later. At the end of a day after the due day, it becomes overdue. Reporting it lost moves it from on loan or from overdue to lost. Giving it back moves it from on loan, overdue, or lost to returned, and fines it for the days it is late. Returned is final. Any event not shown for a state is refused.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> OnLoan : Loan(due day)
OnLoan --> OnLoan : renew [fewer than 2 renewals] / renewals + 1, due day + 14
OnLoan --> Overdue : end of day [today after due day]
OnLoan --> Lost : report lost
Overdue --> Lost : report lost
OnLoan --> Returned : give back / fine for days late
Overdue --> Returned : give back / fine for days late
Lost --> Returned : give back / fine for days late
Returned --> [*]

Read each arrow as a sentence: “when on loan, at the end of a day after the due day, become overdue.” An event that has no arrow out of the current state is not allowed there. The diagram shows that by leaving the arrow out, so the reader must notice what is missing. The next step makes that explicit.

A diagram shows the transitions someone thought of. A state/event table asks about every combination, including the ones nobody thought of:

State ↓ / Event → renew end of day report lost give back
on loan on loan, if < 2 renewals overdue, if after due day lost returned, fined if late
overdue refused refused (already overdue) lost returned, fined if late
lost refused refused refused returned, fined if late
returned refused refused refused refused

Filling in each cell forces a decision. Some of these were not in the statement at all:

  • Overdue, end of day: refused, because the loan is already overdue. It could also be a transition back to overdue that counts the days, but the fine is computed from the dates at return, so nothing needs counting.
  • Lost, give back: the statement says “even if it was lost”, so it is allowed. Without that sentence, someone would have to ask the library.
  • Lost, report lost: refused. Reporting twice is harmless, but “refused” tells the caller that nothing happened.
  • Overdue, renew: refused, as the statement says. A library might later allow renewing an overdue loan after paying the fine; the table is where that change would start.

Every cell that says “refused” is a test case: the event must change nothing.

Here is another way to store the same status, which looks simpler:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

flags.hpp
// A loan's status as three separate yes/no fields. Each can be set on its
// own, so nothing stops a loan from being "lost" and "returned" at once.
struct LoanFlags {
bool overdue = false;
bool lost = false;
bool returned = false;
};
// 2 x 2 x 2 = 8 combinations, but the loan has only 4 states. Which of
// {overdue, lost}, {lost, returned}, or all three at once mean anything?

Three bools have eight combinations, but the loan has four states. The other four (overdue and lost at once, lost and returned, all three…) are impossible states: the type allows them, the diagram does not, and every function must guess what they mean. Each new flag doubles the number of combinations.

An enum class with one enumerator per state makes the impossible states impossible to write by accident (only a deliberate static_cast of a wrong number could force one):

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan.hpp
// The four states of the diagram, and nothing else: a LoanStatus variable
// holds exactly one of them at a time. A new loan starts on_loan; returned
// is final.
enum class LoanStatus { on_loan, overdue, lost, returned };
// The state's name as text, such as "on loan", for printing.
[[nodiscard]] std::string_view to_string(LoanStatus status) noexcept;

A LoanStatus is exactly one of four values. That is the first rule for translating a state diagram into code: one variable holds the state, and its type has exactly the diagram’s states.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan.hpp
// Every event function returns true if the state diagram has a transition
// for it in the current state and its guard is true. Otherwise it returns
// false and changes nothing.
//
// One loan's status, plus the data the events use: the due day, how many
// renewals so far, and the fine. Days are plain day numbers (day 20, day 48).
// [[nodiscard]] on each event: the compiler warns if a caller ignores
// whether the event was accepted.
class Loan {
public:
// The rules, as named constants shared by every Loan (static) and fixed
// when the program is compiled (constexpr).
static constexpr int renewal_days = 14;
static constexpr int max_renewals = 2;
static constexpr std::int64_t fine_per_day_cents = 20;
// A new loan is on loan, due on `due_day`, with no renewals and no fine.
explicit Loan(int due_day) noexcept : due_day_(due_day) {}
// on loan, fewer than 2 renewals: one more renewal, due 14 days later
[[nodiscard]] bool renew();
// on loan, past the due day: becomes overdue
// (On the due day itself the loan is not late yet.)
[[nodiscard]] bool end_of_day(int today);
// on loan or overdue: becomes lost
[[nodiscard]] bool report_lost();
// not yet returned: returned, fined if late
// (20 cents for each day after the due day.)
[[nodiscard]] bool give_back(int today);
[[nodiscard]] LoanStatus status() const noexcept { return status_; }
[[nodiscard]] int due_day() const noexcept { return due_day_; }
[[nodiscard]] int renewals() const noexcept { return renewals_; }
[[nodiscard]] std::int64_t fine_cents() const noexcept { return fine_cents_; }
private:
// The one variable that holds the state. Private, with no setter, so
// only the four event functions can change it.
LoanStatus status_ = LoanStatus::on_loan;
int due_day_;
int renewals_ = 0;
std::int64_t fine_cents_ = 0;
};

The class has one member function per event. Each returns whether the event was accepted, and changes nothing if it was not. Each result is [[nodiscard]], so a caller that ignores it gets a compiler warning. A caller that really does not care, such as a nightly job that sends “end of day” to every loan, says so with static_cast<void>(…). The state is private, with no setter, so only an event can change it, as the invariants lesson recommended.

Each event function is one switch over the current state: one case per row of the table, for that event’s column.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan.cpp
// The "renew" column of the state table. The switch jumps to the case for
// the current state. Several case labels in a row share the code after the
// last of them, so overdue, lost, and returned all reach `return false`.
bool Loan::renew() {
switch (status_) {
case LoanStatus::on_loan:
// Already renewed twice: refuse before changing anything.
if (renewals_ == max_renewals) return false; // guard
++renewals_; // action
due_day_ += renewal_days;
return true; // stays on loan
// Each case ends in `return`, so control never "falls through"
// from one state's code into the next.
case LoanStatus::overdue:
case LoanStatus::lost:
case LoanStatus::returned:
return false; // no transition
}
return false; // not reached: kept for a value outside the enum
}

Each part of the diagram has a place:

  • The state being handled is the case label.
  • The guard is an if that returns false before anything changes.
  • The action is the code that changes the data.
  • The transition is the assignment to status_, or none for a transition back to the same state.
  • Refused events are case labels that return false.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

loan.cpp
// The other three events, written the same way: one switch over the state,
// one case per row of the table, and `return false` for every refusal.
// Sent at the end of each day. Only a loan that is on loan and past its due
// day changes; any other loan ignores the event.
bool Loan::end_of_day(int today) {
switch (status_) {
case LoanStatus::on_loan:
// `<=`: at the end of the due day itself, the loan is not late.
if (today <= due_day_) return false; // guard: not late yet
status_ = LoanStatus::overdue;
return true;
case LoanStatus::overdue:
case LoanStatus::lost:
case LoanStatus::returned:
return false;
}
return false;
}
// A lost report is accepted from on loan or overdue (no guard). A loan that
// is already lost, or has been returned, refuses it.
bool Loan::report_lost() {
switch (status_) {
case LoanStatus::on_loan:
case LoanStatus::overdue:
status_ = LoanStatus::lost;
return true;
case LoanStatus::lost:
case LoanStatus::returned:
return false;
}
return false;
}
// Accepted from every state except returned, including lost: a lost book
// may turn up after all. Returned is final, so a second give_back refuses.
bool Loan::give_back(int today) {
switch (status_) {
case LoanStatus::on_loan:
case LoanStatus::overdue:
case LoanStatus::lost:
// The fine depends on the dates, not on the state: a loan that is
// late but was never marked overdue is fined the same.
// Days late is today - due_day_; std::max(0, ...) turns an early
// return (a negative number) into 0 days. Returned on day 53,
// due day 48: 5 days * 20 cents = 100 cents.
fine_cents_ = std::max(0, today - due_day_) * fine_per_day_cents;
status_ = LoanStatus::returned;
return true;
case LoanStatus::returned:
return false;
}
return false;
}

Two details make the compiler help:

  • No default: label. Every state is listed in every switch. If someone adds a state, say LoanStatus::claimed_returned, then GCC and Clang warn about each switch that does not handle it (-Wswitch, part of -Wall). A default: would silence that warning, and the new state would quietly be treated like whichever states share the default.
  • A return after the switch, which is never reached. A switch over an enum class can, in principle, see a value outside its enumerators (for example, after a bad static_cast), so compilers ask for a return on that path.

Notice also what is not in the state. The fine depends on the dates, not on whether end_of_day was ever called: a loan returned late is fined the same whether or not it was marked overdue first. The state machine decides what is allowed; the data decides how much.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// show (above main) prints the event, whether it was accepted, and the
// loan afterwards. Each event's bool result goes straight into show, so
// none is ignored.
std::cout << "loan A\n";
Loan a(20); // due on day 20; each renewal adds 14 days: 34, then 48
show("renew", a.renew(), a);
show("renew", a.renew(), a);
show("renew", a.renew(), a); // third renewal: guard fails
show("end of day 48", a.end_of_day(48), a); // the due day itself: not late yet
show("end of day 50", a.end_of_day(50), a);
show("renew", a.renew(), a); // overdue loans cannot be renewed
show("give back on day 53", a.give_back(53), a); // 5 days late: 100 cents
std::cout << "loan B\n";
Loan b(20);
show("report lost", b.report_lost(), b);
show("end of day 25", b.end_of_day(25), b); // a lost loan ignores the event
show("give back on day 30", b.give_back(30), b); // found after all
show("give back on day 31", b.give_back(31), b); // returned is final: refused
Expected output
loan A
renew: on loan, due day 34, fine 0 cents
renew: on loan, due day 48, fine 0 cents
renew: refused, still on loan, due day 48, fine 0 cents
end of day 48: refused, still on loan, due day 48, fine 0 cents
end of day 50: overdue, due day 48, fine 0 cents
renew: refused, still overdue, due day 48, fine 0 cents
give back on day 53: returned, due day 48, fine 100 cents
loan B
report lost: lost, due day 20, fine 0 cents
end of day 25: refused, still lost, due day 20, fine 0 cents
give back on day 30: returned, due day 20, fine 200 cents
give back on day 31: refused, still returned, due day 20, fine 200 cents

Loan A is renewed twice, to day 48, and the third renewal fails its guard. At the end of day 48 the loan is not late yet; at the end of day 50 it is. Once overdue, it cannot be renewed. Given back on day 53, it is 5 days late: 100 cents. Loan B is reported lost, ignores the end of the day, and is found and given back on day 30, 10 days late: 200 cents. A second return is refused.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_loan.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if
// the condition is false, and LLD_CHECK_EQ(actual, expected) records a
// failure unless the two are equal, printing both. They come from the
// site's small test header, lld_test.hpp.
// namespace { ... } with no name keeps these helpers private to this file.
namespace {
constexpr int due = 20; // every test loan is due on day 20
// Builds a loan in the given state, using only the public events.
// overdue: the end of day 21, one day late. lost: reported lost. returned:
// given back on the due day (no fine). Each event's result is not needed
// here, so static_cast<void> marks it as ignored on purpose.
Loan loan_in(LoanStatus status) {
Loan loan(due);
switch (status) {
case LoanStatus::on_loan: break;
case LoanStatus::overdue: static_cast<void>(loan.end_of_day(due + 1)); break;
case LoanStatus::lost: static_cast<void>(loan.report_lost()); break;
case LoanStatus::returned: static_cast<void>(loan.give_back(due)); break;
}
return loan;
}
// All four states, to loop over. std::array works out its element type and
// size (LoanStatus, 4) from the values.
constexpr std::array all_states{LoanStatus::on_loan, LoanStatus::overdue, LoanStatus::lost,
LoanStatus::returned};
} // namespace
// The helper itself is checked first, since every later test relies on it.
LLD_TEST(loan_in_builds_each_state) {
for (const LoanStatus status : all_states) LLD_CHECK(loan_in(status).status() == status);
}
namespace {
// Applies one event to a fresh loan in `from`. Checks whether it was
// accepted and, if it was refused, that nothing changed.
// `template <typename Event>` lets `event` be any callable thing; here each
// caller passes a lambda that takes a Loan& and returns the event's bool.
// A fresh loan per call means one check cannot affect the next.
template <typename Event>
void check_event(LoanStatus from, Event event, bool should_accept) {
Loan loan = loan_in(from);
const Loan before = loan; // a copy, to compare with after the event
LLD_CHECK_EQ(event(loan), should_accept);
if (!should_accept) {
LLD_CHECK(loan.status() == before.status());
LLD_CHECK_EQ(loan.due_day(), before.due_day());
LLD_CHECK_EQ(loan.renewals(), before.renewals());
LLD_CHECK_EQ(loan.fine_cents(), before.fine_cents());
}
}
} // namespace
// The whole state table as data: one Row per state, saying which of the four
// events that state accepts. The loop sends every event to a fresh loan in
// every state: 4 x 4 = 16 checks. Days are due + 30 (day 50), well past the
// due day, so end_of_day's guard passes for a loan that is on loan.
LLD_TEST(every_event_in_every_state) {
struct Row {
LoanStatus from;
bool renew, end_of_day, report_lost, give_back; // accepted?
};
const std::array table{
Row{LoanStatus::on_loan, true, true, true, true},
Row{LoanStatus::overdue, false, false, true, true},
Row{LoanStatus::lost, false, false, false, true},
Row{LoanStatus::returned, false, false, false, false},
};
for (const Row& row : table) {
// Each lambda, such as [](Loan& l) { return l.renew(); }, is "send
// this event to loan l". It captures nothing (`[]`).
check_event(row.from, [](Loan& l) { return l.renew(); }, row.renew);
check_event(row.from, [](Loan& l) { return l.end_of_day(due + 30); }, row.end_of_day);
check_event(row.from, [](Loan& l) { return l.report_lost(); }, row.report_lost);
check_event(row.from, [](Loan& l) { return l.give_back(due + 30); }, row.give_back);
}
}
// Where accepted events lead: overdue -> lost on a lost report, and give
// back from each of the three states that allow it ends in returned.
LLD_TEST(each_transition_reaches_the_right_state) {
Loan overdue = loan_in(LoanStatus::overdue);
LLD_CHECK(overdue.report_lost());
LLD_CHECK(overdue.status() == LoanStatus::lost);
// The braces make a temporary list of three states for the loop.
for (const LoanStatus from : {LoanStatus::on_loan, LoanStatus::overdue, LoanStatus::lost}) {
Loan loan = loan_in(from);
LLD_CHECK(loan.give_back(due));
LLD_CHECK(loan.status() == LoanStatus::returned);
}
}
How this code works: How every_event_in_every_state checks 16 cells
  1. The table as data. Each Row is one row of the state table: a starting state and four bools, one per event, saying whether that event should be accepted. The four rows together are the whole table.
  2. The loop. For each row, check_event is called four times, once per event. Each event is passed as a small lambda such as [](Loan& l) { return l.renew(); }, which means “send renew to loan l and hand back its answer”.
  3. check_event builds a fresh loan. loan_in(from) reaches the starting state through public events only, and before is a copy of the loan taken before the event, to compare with afterwards.
  4. It checks the answer. LLD_CHECK_EQ(event(loan), should_accept) sends the event and compares the bool it returns with the table.
  5. For a refusal, it checks that nothing changed. Status, due day, renewals, and fine are each compared with before.

One cell, traced. The row for overdue says renew should be refused. loan_in(LoanStatus::overdue) makes a loan due on day 20 and sends end_of_day(21); 21 is after 20, so the loan becomes overdue. renew() reaches the overdue case and returns false, which matches the table. The status is still overdue, the due day still 20, renewals still 0, and the fine still 0, so all four “nothing changed” checks pass.

check_event is a template (template <typename Event>) because every lambda has its own unnamed type. The compiler writes one version of check_event for each lambda it is called with.

The table is the test plan:

  • loan_in builds a loan in each state through the public events, the way a real loan would get there. There is no back door to set the state.
  • every_event_in_every_state encodes the table: 4 states × 4 events = 16 cells. For each, a fresh loan receives the event, and the test checks whether it was accepted. For each refused cell, it also checks that the status, due day, renewals, and fine did not change.
  • each_transition_reaches_the_right_state checks the target of report lost from overdue, and of give back from each state that allows it. The other targets (on loan to overdue, on loan to lost) are checked by loan_in_builds_each_state and by the guard test.

Further tests in the same file check each guard at its edge (the due day itself is not late, the third renewal is refused) and the fines.

A transition table in data. For machines with many states, the table can be written as data, a std::array or std::map from (state, event) to the next state, and one function looks the answer up. It is compact and easy to compare with the diagram. Guards and actions then need functions in the table, which makes it harder to read. The switch version suits small machines.

The State pattern. Each state becomes a class, with a virtual function per event. That fits when each state has a lot of its own behaviour; for four states and one-line rules, it is far more code. The patterns section covers it.

A std::variant of states. fine_cents_ only means something once the loan is returned. A std::variant<OnLoan, Overdue, Lost, Returned>, where only Returned holds a fine, would make “a fine on a loan still out” impossible as well. The advanced lesson on state machines takes that step.

  • A bool per state, or a bool per condition, instead of one state variable. Impossible combinations follow.
  • A public state, or a set_status, so that any code can move the object to any state, skipping the guards and actions.
  • Checking the state in the callers (if (loan.status() == …) before every call). The object should refuse; callers may ask first.
  • A default: in every switch, which hides new states from the compiler.
  • Only the happy transitions. The refused cells of the table are where the bugs are.
  • States that are really data, such as one_renewal and two_renewals. A count with a guard is simpler than a state per value.

New requirement: “A loan cannot be renewed if another member has placed a hold on the title.”

This is a new guard on the renew transition: renew [fewer than 2 renewals and no holds on the title]. On the diagram, one label changes. In the code, the question is where the information comes from: a Loan does not know about holds, and should not. One choice is for the coordinator (the loan desk, which knows both the loan and the holds) to check holds before calling renew. Another is renew(bool title_has_holds), so the loan’s own rule stays in one place but the caller supplies the fact. The table gains no new state, and every test of the other cells still holds.

Exercise: Complete the missing transitions

A library hold request goes through these states: waiting (in the queue), ready (a copy is kept on the hold shelf), collected, expired (the copy was kept for 7 days and not collected), and cancelled. Someone drew this first version:

A first, incomplete state diagram for a hold request
Text description of the diagram

A hold starts as waiting when it is placed. When a copy is kept, it becomes ready. When it is collected, it becomes collected, which is final. Expired and cancelled are not drawn, and no other transitions are shown.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Waiting : place hold
Waiting --> Ready : copy kept
Ready --> Collected : collect
Collected --> [*]

The events are: copy kept, collect, cancel (by the member), and end of day (checked every night).

  1. Draw the state/event table for the five states and four events, and decide every cell.
  2. Draw the completed diagram, with guards where needed.
  3. Which question would you have to ask the library?
Show the explained answer
  1. One reasonable table:

    State ↓ / Event → copy kept collect cancel end of day
    waiting ready refused cancelled refused (nothing to check)
    ready refused collected cancelled expired, if kept 7 days or more
    collected refused refused refused refused
    expired refused refused refused refused
    cancelled refused refused refused refused
  2. The completed diagram:

The completed state diagram for a hold request
Text description of the diagram

A hold starts as waiting. When a copy is kept, it becomes ready, and the day is recorded. A waiting hold can be cancelled. A ready hold can be collected; or cancelled, which returns the copy to the shelf; or, at the end of a day when the copy has been kept for 7 days or more, it expires, which also returns the copy to the shelf. Collected, cancelled, and expired are final.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Waiting : place hold
Waiting --> Ready : copy kept / record the day
Waiting --> Cancelled : cancel
Ready --> Collected : collect
Ready --> Cancelled : cancel / return copy to the shelf
Ready --> Expired : end of day [kept 7 days or more] / return copy to the shelf
Collected --> [*]
Cancelled --> [*]
Expired --> [*]
  1. Questions the first diagram hid, and the table brought out:
    • Can a member cancel a ready hold? The table says yes, but the library must confirm it, and decide that the copy goes back on the shelf, or to the next member waiting. That action involves other holds, so it belongs to a coordinator, such as the HoldQueue from the invariants lesson, not to one hold.
    • What happens to an expired hold? Does the member go back to the waiting queue, or must they place a new hold? The table above treats expired as final.
    • Can a waiting hold expire, for example after a year? If so, end of day in waiting needs a guard and a transition too.

Note the three final states. Expired, cancelled, and collected each mean the hold is over, but they are kept apart, because reports (“how many holds are never collected?”) need the difference.

  • A state machine lists an object’s states, the events it receives, and the transitions between states, each written event [guard] / action.
  • A state/event table, with every state against every event, finds the transitions a diagram forgot. Each refused cell is a test.
  • Hold the state in one variable whose type has exactly the diagram’s states, an enum class, not a set of bools.
  • Translate the diagram with one member function per event and one switch per function, with no default:, so the compiler warns about unhandled states.
  • The state decides what is allowed; the data decides the details. Do not turn every value into a state.