C++ / CHAPTER 01
Values, expressions, and types
BeginnerTrace small C++17 programs without confusing integer and floating-point arithmetic.
By the end of this chapter
- Initialize typed values
- Trace evaluation with integer operands
- Choose a suitable numeric result type
The idea
Start here if you can read simple arithmetic but have not written C++. A complete console program includes the headers it uses and begins its work in main. A declaration gives an object a type and an initial value. Braces make initialization visible, while const prevents later assignment through that name. The compiler checks types before the program runs; a successful compilation does not prove the calculation matches your intention.
For integer operands, division discards the fractional part toward zero. Converting the completed integer result to double cannot recover the discarded fraction. Convert an operand before division when a fractional result matters. Keep the small values below within range, and distinguish the stored value from how a stream chooses to display it.
#include <iostream>
int main() {
const int items{17};
const int boxes{4};
std::cout << items / boxes << " "
<< static_cast<double>(items) / boxes << "\n";
}4 4.25
The first division uses two integers. The cast changes one operand of the second division, so that calculation retains the fraction.
Try it yourself
Change the values to 23 items and 5 boxes; predict both results before tracing the expression.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING