Operators

Operators in C++: If variables are the nouns of a program, operators are the verbs. means combine, means compare, means "both of these", means store.

The Analogy: The Verbs of the Language

If variables are the nouns of a program, operators are the verbs. + means combine, < means compare, && means "both of these", = means store. A single line like total += price * quantity; is a whole sentence: multiply these two, then add the result to that.

The interesting part is not what each symbol does — most are obvious — but the order in which they act, and the handful that behave differently from every other language you have used.


Syntax or Core Structure

#include <iostream>

int main() {
    int a{10}, b{3};

    // Arithmetic
    std::cout << a + b << "\n";   // 13
    std::cout << a - b << "\n";   // 7
    std::cout << a * b << "\n";   // 30
    std::cout << a / b << "\n";   // 3   <-- integer division, truncated
    std::cout << a % b << "\n";   // 1   <-- remainder (integers only)

    // Comparison -- these produce bool
    std::cout << (a > b) << "\n";    // 1
    std::cout << (a == b) << "\n";   // 0
    std::cout << (a != b) << "\n";   // 1

    // Logical
    bool inRange = (a > 0) && (a < 100);   // both must be true
    bool special = (a == 0) || (b == 0);   // either is enough
    bool nope = !inRange;                  // flip it

    // Assignment shorthands
    a += 5;    // a = a + 5
    a -= 2;    // a = a - 2
    a *= 3;    // a = a * 3
    a /= 4;    // a = a / 4
    a %= 7;    // a = a % 7

    // Increment / decrement
    ++a;       // add one, then give me the new value
    a++;       // give me the old value, then add one

    std::cout << inRange << special << nope << a << "\n";
    return 0;
}

Note that % only works on integers. For floating-point remainders you need std::fmod from <cmath>.


Technical Depth: Precedence, Short-Circuiting and the Traps

Precedence: who goes first

From tightest to loosest, the groups you actually use:

LevelOperatorsNotes
1() [] . ->grouping and member access
2++ -- (prefix) ! - (unary)right to left
3* / %multiplicative
4+ -additive
5< <= > >=relational
6== !=equality — looser than <
7&&logical and
8`\\`logical or — looser than &&
9? :ternary
10= += -= ...assignment, right to left

&& binding tighter than || means a || b && c reads as a || (b && c). Rather than memorising the table, parenthesise anything that is not immediately obvious. Compilers even warn about some of these under -Wall.

Short-circuiting is a feature, not a detail

if (count != 0 && total / count > 10) { /* safe */ }

If count is zero, the left side is false and the right side is never evaluated — no division by zero. && stops at the first false, || stops at the first true. This is guaranteed by the standard, so it is a legitimate way to guard an expensive or dangerous operation:

if (user != nullptr && user->isAdmin()) { /* never dereferences null */ }

Swap the operands and the program crashes. Order matters.

Prefix versus postfix

int i{5};
std::cout << ++i << "\n";   // increments to 6, prints 6
std::cout << i++ << "\n";   // prints 6, THEN increments to 7
std::cout << i   << "\n";   // 7

As a standalone statement they are identical, so ++i; and i++; are interchangeable in a for loop. Inside a larger expression they differ. Prefer ++i as a habit: for heavyweight types postfix has to keep a copy of the old value, which costs.

The ternary operator

int a{7}, b{12};
int larger = (a > b) ? a : b;                      // 12
std::string label = (a % 2 == 0) ? "even" : "odd"; // "odd"

Read it as "condition ? use-this : otherwise-this". Both branches must produce compatible types. It is excellent for a single value choice and awful when nested — use if once you need a second one.

Two genuine traps

int x{5};
if (x = 10) { }   // ASSIGNS 10, then tests 10 as true. Always true!
                  // Wanted: if (x == 10)

if (1 < x < 10) { }  // Compiles, means ((1 < x) < 10)
                     // (1 < x) is 0 or 1, always < 10 -- always true
                     // Wanted: if (1 < x && x < 10)

Both compile without error, which is why they survive. -Wall warns about the first; nothing warns about the second. There is also & versus &&: the single-character version is a bitwise operator that always evaluates both sides, so using it by accident loses short-circuiting.


Real World Example: Shipping Cost Calculator

#include <iostream>
#include <iomanip>

int main() {
    const double itemPrice{24.50};
    const int quantity{3};
    const double weightKg{4.2};
    const bool isMember{true};

    const double subtotal = itemPrice * quantity;

    // Free shipping over 50, otherwise 4.99 plus 1.50 per kg above 2kg
    const bool freeShipping = subtotal >= 50.0 || isMember;
    const double excessWeight = (weightKg > 2.0) ? weightKg - 2.0 : 0.0;
    const double shipping = freeShipping ? 0.0 : 4.99 + excessWeight * 1.50;

    const double discountRate = isMember ? 0.10 : 0.0;
    const double discount = subtotal * discountRate;

    const double total = subtotal - discount + shipping;

    // Split into whole pounds and pence using / and %
    const int totalPence = static_cast<int>(total * 100 + 0.5);   // +0.5 rounds
    const int pounds = totalPence / 100;
    const int pence = totalPence % 100;

    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Subtotal:  " << subtotal << "\n";
    std::cout << "Discount:  -" << discount << "\n";
    std::cout << "Shipping:  " << shipping << "\n";
    std::cout << "Total:     " << pounds << "." << std::setw(2)
              << std::setfill('0') << pence << "\n";
    return 0;
}

Three operator ideas carry this program. The ternary picks between two values without an if block. || short-circuits, so a member never needs the subtotal checked. And the / 100 and % 100 pair splits a pence total into pounds and pence — the classic use of integer division working with you rather than against you. The + 0.5 before the cast rounds instead of truncating, because static_cast<int> always chops.


Common Mistakes

  • = instead of == in a condition. Assigns and then tests, so the branch is almost always taken.
  • Chained comparisons like 1 < x < 10. Legal C++, wrong meaning. Use &&.
  • Assuming / gives a decimal. sum / count with two ints truncates. Cast one side: sum / static_cast<double>(count).
  • Using & and | where you meant && and ||. You lose short-circuiting, so a null check stops protecting you.
  • Relying on evaluation order in f(i++, i) or arr[i] = i++. The order is unspecified; the result is unreliable across compilers.
  • % on doubles. It does not compile. Use std::fmod.
  • Forgetting that -1 % 5 is -1, not 4. C++ truncates toward zero, unlike Python.

Best Practices

  1. Parenthesise for readers, not for the compiler. (a && b) || c costs nothing and removes all doubt.
  2. Put the cheap or protective test first in an && chain so short-circuiting works for you.
  3. Prefer ++i over i++ when the value is not used.
  4. Use compound assignment (total += x) — it says "update in place" and cannot mistype the variable name twice.
  5. Use the ternary for a single value choice only. Nested ternaries are write-only code.
  6. Compile with -Wall -Wextra. It catches the =-for-== slip and much else.

Practice Exercises

  1. Digit splitter: Read a three-digit integer and print its hundreds, tens and units digits using only / and %.
  2. Leap year one-liner: Write a single boolean expression that is true for leap years — divisible by 4, except centuries, unless divisible by 400 — and test it on 1900, 2000, 2024 and 2025.
  3. Trap hunt: Write a program containing if (x = 5) and if (1 < x < 10), compile it with -Wall -Wextra, and record which one the compiler warns about. Then fix both.
  4. Precedence audit: Predict the value of 2 + 3 * 4 % 5, !0 == 1, 10 - 4 - 3 and a++ + ++a on paper first, then run them and compare. Rewrite each one with parentheses so a reader needs no precedence table, and for the last expression explain in a comment why your prediction was not guaranteed to be right in the first place.