Modern C++ • C++20 baseline
Operators, Conversions, and Integer Arithmetic
Understand promotions and avoid losing information during arithmetic.
C++ applies integral promotions and usual arithmetic conversions before many operators. Dividing two integers produces an integer result, and converting a floating-point result to an integer discards the fractional portion. Use explicit conversions only when the loss is intended and safe; for untrusted arithmetic, check bounds before the operation.
Key points
- Integer division truncates toward zero.
- Unsigned arithmetic wraps modulo its range; signed overflow is undefined behavior.
Example
#include <iostream>
int main() {
const int whole = 17 / 5;
const double ratio = 17.0 / 5.0;
std::cout << whole << ' ' << ratio << '\n';
}
What to expect
3 3.4
Practice exercise
Compute a percentage using integers and then doubles. Explain the difference before formatting the output.
Key idea: Know the operand types before evaluating an expression.