Increment, Assignment, Ternary & Bitwise
Increment & decrement
| Form | Effect | Value of the expression |
|---|---|---|
++i (pre) | add 1 | the new value |
i++ (post) | add 1 | the old value |
--i, i-- | subtract 1 | same idea |
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
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)
| Op | Name | Example (5 = 0101, 3 = 0011) |
|---|---|---|
& | AND | 5 & 3 = 1 (0001) |
| | OR | 5 | 3 = 7 (0111) |
^ | XOR | 5 ^ 3 = 6 (0110) |
~ | NOT | flips every bit |
<< | left shift | 1 << 3 = 8 (multiply by 2³) |
>> | right shift | 16 >> 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
#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
*/