C++

Chapter 3: Operators - Making Your C++ Program Calculate and Compare

By Ali Naqi • October 21, 2025

Chapter 3: Operators - Making Your C++ Program Calculate and Compare

C++ Tutorial Series - Chapter 3: Operators - Calculation, Comparison, and Control

In Chapter 2, we taught our C++ program how to remember things using variables. Now, it's time to teach it how to think and act. Operators are the verbs of the C++ language—they tell the compiler to perform actions on your variables. We’ll break down all the major operator categories and resolve the most common beginner confusion: integer division and the difference between prefix and postfix increments.

1. The Arithmetic Arsenal (Math Operations)

These are the symbols you use for basic math. They are straightforward, but two require special attention: division and the modulus operator.

Operator Name Function
+AdditionCalculates the sum.
-SubtractionCalculates the difference.
*MultiplicationCalculates the product.
/DivisionCalculates the quotient. (Be careful with integers!)
%ModulusCalculates the remainder of an integer division.

The Hidden Trap: Integer Division

This is a major source of bugs for beginners. When both operands of the division operator (/) are integers, C++ performs integer division, meaning the result is always an integer, and the fractional part is simply dropped (truncated), not rounded.


int fullScore = 100;
int maxQuestions = 15;

// The result is 6, NOT 6.666...
int scorePerQuestion = fullScore / maxQuestions; 
std::cout << "Score per question: " << scorePerQuestion << std::endl; // Output: 6

// How to fix it (as learned in Chapter 2: Type Casting)
double preciseScore = static_cast<double>(fullScore) / maxQuestions;
std::cout << "Precise Score: " << preciseScore << std::endl; // Output: 6.666...
    

The Modulus Operator (%)

The modulus operator is invaluable for determining if a number is odd/even, cycling through arrays, or checking divisibility. It gives you the remainder after integer division.


// Example: Checking for Even/Odd
int myNum = 17;
int remainder = myNum % 2; // Remainder of 17 / 2 is 1

std::cout << "Remainder: " << remainder << std::endl; // Output: 1 (It's odd)
    

2. Assignment and Compound Assignment Operators

The basic assignment operator is the single equals sign (=). It means "put the value of the right-hand side into the variable on the left-hand side."

Compound Assignment (Shorthand)

To keep your code clean and concise, C++ offers compound operators that combine an arithmetic operation and an assignment.

OperatorExampleIs equivalent to...
+=x += 5;x = x + 5;
-=x -= 10;x = x - 10;
*=x *= 2;x = x * 2;
/=x /= 4;x = x / 4;

3. The Increment/Decrement Puzzle (++ and --)

These operators are used constantly in C++ (especially in loops). They simply add or subtract 1 from a variable. However, the placement is extremely important when they are used within a larger expression.

Postfix (i++ or i--) vs. Prefix (++i or --i)

This is where the subtle power of C++ lies. Pay close attention to the order of operations here:

  1. Postfix (i++): Use then Change. The variable's original value is used in the expression, and then the variable is incremented.
  2. Prefix (++i): Change then Use. The variable is incremented first, and then the new value is used in the expression.

int counter = 10;
int result;

// 1. POSTFIX Example
result = counter++; // 'result' gets 10, THEN 'counter' becomes 11
std::cout << "Postfix Result: " << result << std::endl;  // Output: 10
std::cout << "Counter Value: " << counter << std::endl; // Output: 11

// Reset
counter = 10; 

// 2. PREFIX Example
result = ++counter; // 'counter' becomes 11, THEN 'result' gets 11
std::cout << "Prefix Result: " << result << std::endl;   // Output: 11
std::cout << "Counter Value: " << counter << std::endl; // Output: 11
    
Optimization Tip: In modern C++, for simple incrementing outside of expressions (e.g., in a for loop update), the prefix form (++i) is often slightly more efficient for complex data types. Make it a habit!

4. Relational and Logical Operators (The Decision Makers)

These operators are fundamental for making decisions and controlling the flow of your program (which we cover in Chapter 4!). They always return a bool value (true or false).

Relational Operators (Comparison)

Compare two operands.

OperatorMeaning
==Is equal to (The equality check. DO NOT confuse with =!)
!=Is not equal to
>Is greater than
<Is less than
>=Is greater than or equal to
<=Is less than or equal to

Logical Operators (Combining Results)

Combine two or more boolean expressions.

OperatorMeaning
&&Logical AND: True only if BOTH sides are true.
||Logical OR: True if AT LEAST ONE side is true.
!Logical NOT: Reverses the result (true becomes false, and vice versa).

int age = 20;
bool hasLicense = true;

// Relational result: (20 >= 18) is TRUE
bool isAdult = (age >= 18); 

// Logical result: (TRUE && TRUE) is TRUE
bool canRentCar = (isAdult && hasLicense);
    

5. Operator Precedence (The Order of Operations)

When you have a complex expression, how does the compiler know which operation to perform first? It uses precedence. Just like in algebra (PEMDAS/BODMAS), C++ has rules to dictate the order of evaluation. This is critical!

A simplified, high-level order (highest precedence first):

  1. Parentheses () (Highest: use them to force an order!)
  2. Unary (like ++, --, !)
  3. Multiplicative (*, /, %)
  4. Additive (+, -)
  5. Relational (<, >, <=, >=)
  6. Equality (==, !=)
  7. Logical AND (&&)
  8. Logical OR (||)
  9. Assignment (=, +=, etc.) (Lowest)

int x = 5 + 3 * 2; 
// Precedence says multiplication first: 5 + (3 * 2) = 11

int y = (5 + 3) * 2;
// Parentheses force addition first: (8) * 2 = 16
    
Rule of Thumb: Even if you know the precedence rules, use parentheses to make complex expressions unambiguous. Clear code is always better than clever code.

Chapter 3 Conclusion and Next Steps

Operators are the action layer of your program. You've learned how to calculate accurately (avoiding integer division traps!), how to increment variables efficiently (prefix vs. postfix), and how to generate the crucial true/false results needed for decision-making.

In Chapter 4, we will use those true/false results generated by relational and logical operators to build powerful Control Flow structures—the if, else, and switch statements—allowing your program to choose its path. Get ready to teach your code to think!