Skip to main content
Module 1 · Lesson 2 of 32/26 in the course~10 min
Module lessons (2/3)

Operators

Practice Stage

Expressions and safe precedence

Combine arithmetic and Boolean logic while avoiding truncated divisions and side-effects.

Operators in C++ transform values and expressions into new typed results. Understanding exactly which type each operator produces prevents the most frequent numerical errors in real systems.

1. Arithmetic and the Integer Division Trap

OperatorOperationExample expressionResult
+, -Addition and subtraction12 + 8 - 317
*Multiplication6 * 742
/Division (integer if both int)5 / 2 vs 5.0 / 22 / 2.5
%Modulo (integer remainder, only integers)17 % 52
C++
#include <iostream>

int main() {
    int a {7};
    int b {2};

    int intDiv = a / b;                            // 3 (troncato!)
    double exactDiv = static_cast<double>(a) / b;  // 3.5 (almeno un operando double)
    int rem = a % b;                               // 1

    std::cout << intDiv << " | " << exactDiv << " | resto=" << rem << "\n";
    return 0;
}

2. Compound Assignment and Increment (++x vs x++)

The operators +=, -=, *=, /= update a variable in place avoiding repetitions:

C++
#include <iostream>

int main() {
    int credits {10};
    credits += 5;   // 15
    credits *= 2;   // 30
    ++credits;      // prefisso: incrementa prima di usare (31)

    std::cout << "Crediti finali: " << credits << "\n";
    return 0;
}

3. Comparison (==, !=) and Logic with Short-Circuit (&&, ||, !)

Comparisons produce bool (true or false). With && (AND) and || (OR), C++ guarantees short-circuit evaluation: if the left side already decides the outcome, the right side is not evaluated.

C++
#include <iostream>

int main() {
    int total {100};
    int count {0};

    // Sicuro: count != 0 è false, quindi total / count non viene eseguito!
    bool highAvg = (count != 0) && ((total / count) > 20);
    std::cout << std::boolalpha << highAvg << "\n";
    return 0;
}

4. Precedence and Clear Parentheses

The operator ! has higher priority than &&, which in turn precedes ||; arithmetic * / % precede + -, which precede == !=. Always put parentheses when mixing logic and comparison!

C++
#include <iostream>

int main() {
    int age {20};
    bool hasPass {true};
    bool isVip {false};

    bool allowed = ((age >= 18) && hasPass) || isVip;
    std::cout << std::boolalpha << allowed << "\n";
    return 0;
}

Practical exercises

Exercise#cpp.m1.l2.e1
Attempts: 0Loading…

Calculate the remainder of the division of 17 by 5 using the % operator, save it in int remainder and print it with std::cout.

Loading editor…
Show hint

Use int remainder = 17 % 5; and print remainder on std::cout.

Solution available after 3 attempts

Exercise#cpp.m1.l2.e2
Attempts: 0Loading…

Given int age = 20; and bool hasLicense = true;, compute bool canDrive verifying that age >= 18 and hasLicense are both true via &&, then print canDrive.

Loading editor…
Show hint

Write bool canDrive = (age >= 18) && hasLicense; followed by std::cout << canDrive;.

Solution available after 3 attempts

Exercise#cpp.m1.l2.e4
Attempts: 0Loading…

Given int sum = 9; and int n = 2;, calculate the real mean in double average avoiding integer truncation with static_cast<double>(sum) / n and print it.

Loading editor…
Show hint

Convert sum to static_cast<double>(sum) before dividing by n.

Solution available after 3 attempts

Check for understanding

Quiz#cpp.m1.l2.e3
Ready

What value does ratio take on after executing this fragment?

C++
int a = 5;
int b = 2;
double ratio = a / b;
Answer options
Quiz#cpp.m1.l2.e5
Ready

Why doesn't (ptr != nullptr) && (*ptr > 0) cause null pointer dereference when ptr == nullptr?

C++
int* ptr = nullptr;
bool positive = (ptr != nullptr) && (*ptr > 0);
Answer options