Lesson 5 — Fundamentals

Operators

Operators let you combine, compare, and manipulate values. C++ groups them into arithmetic, relational, logical, and assignment categories, each with its own precedence rules.

Arithmetic and Assignment Operators

The standard arithmetic operators (+ - * / %) behave as expected, with one caveat: dividing two integers performs integer division, discarding any remainder. Compound assignment operators like += update a variable in place.

C++ — Arithmetic pitfalls
int a = 7, b = 2;
std::cout << a / b << std::endl;       // 3 (integer division)
std::cout << a % b << std::endl;       // 1 (remainder)
std::cout << (double)a / b << std::endl; // 3.5 (cast to force decimal)

int score = 10;
score += 5;  // same as score = score + 5
score *= 2;  // same as score = score * 2

Relational and Logical Operators

Relational operators compare two values and produce a bool. Logical operators combine boolean expressions, which is how conditions with multiple requirements are built.

  • == != > < >= <= — comparison, all return bool.
  • && — logical AND, true only if both sides are true.
  • || — logical OR, true if at least one side is true.
  • ! — logical NOT, flips a boolean value.

Common Mistakes

  • Using a single = (assignment) when you meant == (comparison) inside a condition.
  • Forgetting that integer division truncates — 7 / 2 is 3, not 3.5.
  • Mixing up && and || when combining multiple conditions.
  • Not using parentheses to clarify operator precedence in a complex expression.

Professional Tip

When in doubt about precedence, add parentheses. (a + b) * c is always clearer to a future reader than relying on memorised operator precedence rules.

Your Turn

Write a program that takes two integers, and prints whether the first is greater than, less than, or equal to the second, using relational operators and an if / else if / else chain.

Mini Quiz

What does the expression 9 % 4 evaluate to in C++?