C++ · Module 4 · Lesson 22 min read

Increment, Assignment, Ternary & Bitwise

Increment & decrement

FormEffectValue of the expression
++i (pre)add 1the new value
i++ (post)add 1the old value
--i, i--subtract 1same idea
CSS
int i = 5;
int a = ++i;   // i = 6, a = 6
int b = i++;   // b = 6, i = 7

✅ Prefer ++i when you don't need the old value (it can be cheaper for iterators). ⚠️ Never modify the same variable twice in one expression (i = i++ + ++i; — undefined/unspecified).

Compound assignment

+= -= *= /= %= &= |= ^= <<= >>= total += price; is the same as total = total + price;

Ternary (conditional) operator

c
condition ? value_if_true : value_if_false
std::string status = (balance >= 0) ? "OK" : "Overdrawn";

Great for simple choices. Don't nest them deeply — use if instead.

Bitwise operators (work on individual bits)

OpNameExample (5 = 0101, 3 = 0011)
&AND5 & 3 = 1 (0001)
|OR5 | 3 = 7 (0111)
^XOR5 ^ 3 = 6 (0110)
~NOTflips every bit
<<left shift1 << 3 = 8 (multiply by 2³)
>>right shift16 >> 2 = 4

Common bit tricks

  • Is n even? (n & 1) == 0
  • Set bit k: flags |= (1 << k)
  • Clear bit k: flags &= ~(1 << k)
  • Toggle bit k: flags ^= (1 << k)
  • Test bit k: (flags >> k) & 1
  • std::bitset<8> (<bitset>) prints numbers in binary

Use bitwise operators on unsigned types to avoid sign surprises.

Example

C++
#include <bitset>
#include <iostream>
#include <string>

int main() {
    int i = 5;
    int a = ++i;          // pre: increment, then use
    int b = i++;          // post: use, then increment
    std::cout << "a=" << a << " b=" << b << " i=" << i << '\n';

    double balance = 1000;
    balance -= 250;
    balance *= 2;
    std::cout << "balance=" << balance << '\n';

    std::string status = (balance >= 0) ? "OK" : "Overdrawn";
    std::cout << "status: " << status << ", parity of 7: " << ((7 % 2 == 0) ? "even" : "odd") << '\n';

    unsigned x = 5, y = 3;
    std::cout << "5 & 3 = " << (x & y) << ", 5 | 3 = " << (x | y) << ", 5 ^ 3 = " << (x ^ y) << '\n';
    std::cout << "1 << 4 = " << (1u << 4) << ", 100 >> 2 = " << (100u >> 2) << '\n';

    // Permission flags stored in one byte
    constexpr unsigned READ = 1 << 0, WRITE = 1 << 1, SHARE = 1 << 2;
    unsigned perms = 0;
    perms |= READ | SHARE;                  // set two flags
    std::cout << "perms = " << std::bitset<4>(perms) << '\n';
    perms ^= WRITE;                         // toggle WRITE on
    perms &= ~SHARE;                        // clear SHARE
    std::cout << "perms = " << std::bitset<4>(perms) << ", can write? " << std::boolalpha << ((perms & WRITE) != 0) << '\n';
    std::cout << "42 in binary: " << std::bitset<8>(42) << '\n';
    return 0;
}

/* Output:
a=6 b=6 i=7
balance=1500
status: OK, parity of 7: odd
5 & 3 = 1, 5 | 3 = 7, 5 ^ 3 = 6
1 << 4 = 16, 100 >> 2 = 25
perms = 0101
perms = 0011, can write? true
42 in binary: 00101010
*/