C++ ยท Chapter 10 of 49

C++ Operators

C++ provides arithmetic (`+ - * / %`), assignment (`= += -=`), comparison (`== != < >`) and logical (`&& || !`) operators. Operator precedence follows mathematical convention, and parentheses can force evaluation order.

Increment/decrement operators `++`/`--` are heavily used in loops, and come in prefix (`++i`) and postfix (`i++`) forms with subtly different behaviour.

Arithmetic and assignment

`%` gives the remainder of integer division. Compound assignment like `x += 5` is shorthand for `x = x + 5`.

Comparison and logical

Comparisons return a bool. `&&` (AND), `||` (OR) and `!` (NOT) combine boolean expressions, and short-circuit evaluation skips unnecessary checks.

Example 1 (cpp)
int a = 7, b = 2;
std::cout << a % b << " " << (a > b);
Output
1 1

7 % 2 is 1 (remainder); a > b is true (1).

Example 2 (cpp)
int i = 5;
std::cout << i++ << " " << i;
Output
5 6

Postfix i++ returns the old value, then increments.

Key points

  • Arithmetic: + - * / %; assignment: = += -= *= /=.
  • Comparison operators return bool.
  • && and || short-circuit evaluation.
  • Prefix ++i increments then returns; postfix i++ returns then increments.
๐Ÿ’ก Note: Integer division truncates: 7 / 2 gives 3, not 3.5 โ€” cast to double if you need a fractional result.

๐Ÿ“ Quick Quiz

1. What does 7 % 2 evaluate to?

2. Which operator is logical AND?

3. What does i++ do compared to ++i?