Module lessons (2/3)
Operators
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
| Operator | Operation | Example expression | Result |
|---|---|---|---|
+, - | Addition and subtraction | 12 + 8 - 3 | 17 |
* | Multiplication | 6 * 7 | 42 |
/ | Division (integer if both int) | 5 / 2 vs 5.0 / 2 | 2 / 2.5 |
% | Modulo (integer remainder, only integers) | 17 % 5 | 2 |
#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:
#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.
#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!
#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
Calculate the remainder of the division of 17 by 5 using the % operator, save it in int remainder and print it with std::cout.
Show hint
Use int remainder = 17 % 5; and print remainder on std::cout.
Solution available after 3 attempts
Given int age = 20; and bool hasLicense = true;, compute bool canDrive verifying that age >= 18 and hasLicense are both true via &&, then print canDrive.
Show hint
Write bool canDrive = (age >= 18) && hasLicense; followed by std::cout << canDrive;.
Solution available after 3 attempts
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.
Show hint
Convert sum to static_cast<double>(sum) before dividing by n.
Solution available after 3 attempts
Check for understanding
What value does ratio take on after executing this fragment?
int a = 5;
int b = 2;
double ratio = a / b;Why doesn't (ptr != nullptr) && (*ptr > 0) cause null pointer dereference when ptr == nullptr?
int* ptr = nullptr;
bool positive = (ptr != nullptr) && (*ptr > 0);