i++, ++i and compound assignment
i++ and ++i both add one. They differ in the value the expression hands back: the old one or the new one. Compound operators like |= and &= ~ are how firmware sets and clears bits in registers.
Pre- and post-increment
increment.cppC++
#include <iostream>int main() { int i = 5; int a = i++; // a gets 5, then i becomes 6 int b = ++i; // i becomes 7, then b gets 7 std::cout << "a=" << a << " b=" << b << " i=" << i << '\n';}
Output
a=5 b=7 i=7
Decrement works the same way with i-- and --i.
Compound assignment
x += 3 means x = x + 3, and the same pattern works for every operator. The bitwise ones matter most in firmware: |= sets bits, &= ~ clears them and ^= toggles them, as in the Registers insight.
bits.cppC++
#include <cstdint>#include <iostream>int main() { std::uint8_t reg = 0b0000'0000; reg |= (1u << 3); // set bit 3 reg |= (1u << 0); // set bit 0 reg &= ~(1u << 0); // clear bit 0 reg ^= (1u << 7); // toggle bit 7 std::cout << static_cast<int>(reg) << '\n';}
Output
136