C++ programming 2 min read

if/else and switch

if/else chooses between paths using a condition, and switch jumps to the case that matches a value. Firmware often combines them into a state machine: one switch on the current state, run on every pass of the main loop.

Left: if temp > 30 is true, fan_on() runs, otherwise fan_off(); both continue to the next statement. Right: switch (state) jumps to the matching case, IDLE, RUN or ERROR, or to default, and each case breaks to the next statement.
if/else picks a path; switch jumps to the matching case.

if / else

fan.cppC++
#include <iostream>int main() {    int temp = 34;    if (temp > 30) {        std::cout << "fan on\n";    } else {        std::cout << "fan off\n";    }}
Output
fan on

A switch-based state machine

A state machine remembers which mode the device is in. On each pass, a switch runs the code for the current state and decides the next one. That keeps complicated behaviour in small, testable steps.

state.cppC++
#include <iostream>enum class State { Idle, Run, Error };State step(State s, bool button, bool fault) {    switch (s) {    case State::Idle:        return button ? State::Run : State::Idle;    case State::Run:        return fault ? State::Error : State::Run;    case State::Error:        return State::Error;   // stays here until reset    }    return s;}int main() {    State s = State::Idle;    s = step(s, true, false);   // button pressed    s = step(s, false, true);   // fault detected    std::cout << (s == State::Error ? "Error" : "OK") << '\n';}
Output
Error