CKTIS / C++
Finite-state machines
A finite-state machine (FSM) describes behavior using a finite set of states and event-driven transitions. In C++, enum class and a transition function can represent the model while making each next-state rule explicit.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
enum class State { locked, unlocked };
enum class Event { coin, push };
constexpr State transition(State state, Event event);A finite-state machine (FSM) has a finite set of states, an initial state, a set of events, and transition rules. In a deterministic machine, each current-state/event pair determines exactly one next state. This is a modeling pattern, not a separate C++ syntax construct.
In the example, a turnstile starts in State::locked. Event::coin unlocks it, and Event::push locks an unlocked turnstile again. Pushing a locked turnstile and inserting a coin into an unlocked turnstile leave the state unchanged: these are explicitly defined self-transitions. The transition function computes the next state without side effects; main stores and prints the result.
enum class creates distinct state and event types. switch selects a branch by state; each branch ends with return, so execution cannot fall through to the next label. The rules cover all four combinations of named values, checked by static_assert. The final return state is not validation: enumeration values created by explicit casts outside the named set are outside this model and require separate checking at the input boundary.
When extending the machine, define what every state/event pair means: a transition, staying in place, or an explicit error. Test event sequences as well as individual transitions. The example targets C++23 compilation; the referenced source is an evolving working draft, not a frozen C++23 publication.
Examples
#include <iostream>
enum class State { locked, unlocked };
enum class Event { coin, push };
constexpr State transition(State state, Event event) {
switch (state) {
case State::locked:
return event == Event::coin ? State::unlocked : State::locked;
case State::unlocked:
return event == Event::push ? State::locked : State::unlocked;
}
return state;
}
static_assert(transition(State::locked, Event::coin) == State::unlocked);
static_assert(transition(State::locked, Event::push) == State::locked);
static_assert(transition(State::unlocked, Event::coin) == State::unlocked);
static_assert(transition(State::unlocked, Event::push) == State::locked);
int main() {
State state = State::locked;
constexpr Event events[] = {
Event::push, Event::coin, Event::coin, Event::push
};
for (Event event : events) {
state = transition(state, event);
std::cout << (state == State::locked ? "locked" : "unlocked") << '\n';
}
}
Result
locked unlocked unlocked locked
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.