C++ · Module 4 · Lesson 12 min read

Arithmetic, Relational & Logical Operators

Arithmetic operators

OpMeaningExampleResult
+ - *add, subtract, multiply7 * 321
/divide7 / 2 → 3 (ints) · 7 / 2.0 → 3.5
%remainder (integers only)7 % 31
unary -negate-x
  • % with negatives: the result has the sign of the left operand (-7 % 3 → -1)
  • For doubles use std::fmod (<cmath>)
  • Division by zero with integers is undefined behaviour — check first!

Relational operators (result is bool)

== equal · != not equal · < · > · <= · >= ⚠️ = assigns, == compares. if (x = 5) is a classic bug (compilers warn).

Logical operators

OpMeaningShort-circuit
&&ANDstops if left is false
||ORstops if left is true
!NOT—

Short-circuiting lets you write safe checks:

scss
if (count != 0 && total / count > 100)   // no division by zero

C++ also accepts the words and, or, not.

Precedence (high → low, simplified)

  1. () · function calls · []
  2. unary ! - ++ --
  3. * / %
  4. + -
  5. < <= > >=
  6. == !=
  7. &&
  8. ||
  9. ?: and assignment = += -=

✅ When in doubt, use parentheses. They cost nothing and make intent clear.

Common traps

  • 5 / 2 * 2 → 4 (integer division first)
  • a < b < c doesn't mean "b is between a and c" — write a < b && b < c
  • !x == 5 means (!x) == 5

Example

C++
#include <cmath>
#include <iostream>

int main() {
    int a = 17, b = 5;
    std::cout << "a + b = " << a + b << ", a - b = " << a - b << ", a * b = " << a * b << '\n';
    std::cout << "a / b = " << a / b << ", a % b = " << a % b << ", -a % b = " << -a % b << '\n';
    std::cout << "17.0 / 5 = " << 17.0 / 5 << ", fmod(17.5, 5) = " << std::fmod(17.5, 5) << '\n';

    std::cout << std::boolalpha;
    std::cout << "a > b: " << (a > b) << ", a == b: " << (a == b) << ", a != b: " << (a != b) << '\n';

    int income = 40000, expenses = 52000;
    bool overspent = expenses > income;
    bool has_savings = false;
    std::cout << "Need a warning? " << (overspent && !has_savings) << '\n';

    int count = 0, total = 500;
    if (count != 0 && total / count > 100)        // short-circuit avoids dividing by zero
        std::cout << "high average\n";
    else
        std::cout << "no items yet\n";

    std::cout << "2 + 3 * 4 = " << 2 + 3 * 4 << ", (2 + 3) * 4 = " << (2 + 3) * 4 << '\n';
    std::cout << "5 / 2 * 2 = " << 5 / 2 * 2 << '\n';
    int age = 25;
    std::cout << "18 <= age <= 30? " << (18 <= age && age <= 30) << '\n';
    return 0;
}

/* Output:
a + b = 22, a - b = 12, a * b = 85
a / b = 3, a % b = 2, -a % b = -2
17.0 / 5 = 3.4, fmod(17.5, 5) = 2.5
a > b: true, a == b: false, a != b: true
Need a warning? true
no items yet
2 + 3 * 4 = 14, (2 + 3) * 4 = 20
5 / 2 * 2 = 4
18 <= age <= 30? true
*/