C++ programming 3 min read

Loops

A loop repeats a block while a condition holds. Firmware lives inside one: the super-loop while (true) that reads inputs, updates state and drives outputs until the power goes off.

Three flowcharts summing 1 to 10. while checks i <= 10 before running the body, so the body may never run. do-while runs the body first and checks afterwards, so it always runs at least once. for sets int i = 1, checks i <= 10, runs sum += i, then updates ++i and checks again. All three leave the loop when the condition is false.
Three loops, one idea: check, run, update.

Three loops, one idea

while checks its condition first, so the body may never run. do … while runs the body once before checking. for puts the start value, the condition and the update on one line, which suits counting.

sum.cppC++
#include <iostream>int main() {    int sum = 0;    for (int i = 1; i <= 10; ++i) {        sum += i;    }    std::cout << "Sum: " << sum << '\n';}
Output
Sum: 55

The super-loop

A microcontroller has no operating system to return to, so main() never ends. After setting up the hardware, it repeats the same steps forever.

main.cppC++
void init_hardware();void read_buttons();void update_state();void drive_leds();int main() {    init_hardware();    while (true) {      // runs until the power goes off        read_buttons();        update_state();        drive_leds();    }}