C++ programming 2 min read

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.

With y = i++, y gets the old value 5 and then i becomes 6. With y = ++i, i becomes 6 first and y gets the new value 6. Both add 1 to i.
Post-increment hands back the old value, pre-increment the new one.

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