1. Goals
You will choose types for simple data, initialize variables before using them,
and explain why division can lose its fractional part even when stored in a double.
You will also understand that a cast does not check the destination's range for you.
2. Prerequisites
Know how to save
main.cpp, compile it in C++17 mode, and run the program.Recognize
main,std::cout, semicolons, and the newline character'\n'.Understand ordinary addition, subtraction, multiplication, and division.
3. Explanation
A variable gives data a name. In int books = 7;, int is the type,
books is the name, and 7 is the initial value. A type determines which values
can be stored and how calculations work, not just how data appears on screen.
int: signed whole numbers, such as7,0, and-3.double: floating-point numbers, useful for fractional values such as12.5. Many decimal fractions cannot be represented exactly; it is not an unlimited real number.bool: eithertrueorfalse, suitable for a yes/no state.char: one character unit, such as'A'in single quotes. A Vietnamese letter in UTF-8 can need severalcharunits; a later lesson uses strings for text.
Provide an initial value when declaring a variable. Writing int books; inside
main does not automatically set it to 0; reading it before assigning a value
is an error in this C++17 example. int books = 0; has an explicit initial value.
After creating the variable, books = 8; replaces its existing value.
The declaration const int readers = 2; creates an integer that cannot be assigned
a new value after initialization. Use const for data you intend to keep unchanged;
the compiler rejects readers = 3;. Initialization and later assignment are different operations.
Basic arithmetic operators are +, -, *, and /. With two integers,
7 / 2 produces 3, and 7 % 2 produces the remainder 1.
Integer division discards the fractional part toward zero: -7 / 2 produces -3.
Never divide or take a remainder by zero. See the
C++ draft rules for division and remainder.
The declaration double average = 7 / 2; still stores only 3: integer division happened first.
Use 7.0 / 2 or static_cast<double>(books) / readers for floating-point division.
The expression static_cast<double>(books) requests conversion to double;
in this small example, 7 is represented exactly, and the result is 3.5.
In the other direction, static_cast<int>(12.5) produces 12, not rounding to the nearest integer.
The expression static_cast<int>(-12.5) produces -12. Only do this when the value
is finite and its integer part fits in int; otherwise the behavior is undefined.
A static_cast expresses your intent without checking that condition for you.
The floating-point to integer conversion rules
describe this discarded fraction and the range requirement.
The range of int depends on the implementation; do not assume every machine uses 32 bits.
Add #include <limits> and place these lines inside main to inspect your machine's range:
std::cout << std::numeric_limits<int>::lowest() << '\n';
std::cout << std::numeric_limits<int>::max() << '\n';Read std::numeric_limits<int> as information about the limits of int.
The functions lowest() and max() return its lowest and highest values.
These numbers can differ between systems, so they are not part of the fixed output below.
For floating-point types, min() does not mean the most negative value; use lowest().
The C++ numeric limits reference defines these names.
An unsigned int only stores nonnegative values, but does not prevent every arithmetic mistake.
Mixing signed and unsigned values can change the meaning of a comparison:
-1 < 1u is false because -1 is converted to unsigned int; the suffix u makes an unsigned literal.
For now, prefer matching int variables for the small counts used in this lesson.
Signed integer arithmetic overflow has undefined behavior: you cannot rely on a value wrapping around. Unsigned arithmetic works modulo its representable range, but a wrapped result can still be wrong for your task. Choose a sufficiently wide type and check limits before calculating; casting a result after overflow does not repair the earlier operation.
4. Runnable example
Save as main.cpp and use the C++17 command from the previous lesson. No input is needed.
#include <iostream>
int main() {
int books = 7;
const int readers = 2;
int each = books / readers;
int remaining = books % readers;
double average = static_cast<double>(books) / readers;
double length = 12.5;
int wholeLength = static_cast<int>(length);
char shelf = 'A';
bool available = true;
std::cout << "Books: " << books << '\n';
std::cout << "Each: " << each << '\n';
std::cout << "Remaining: " << remaining << '\n';
std::cout << "Average: " << average << '\n';
std::cout << "Length: " << length << '\n';
std::cout << "Whole length: " << wholeLength << '\n';
std::cout << "Shelf: " << shelf << '\n';
std::cout << std::boolalpha << "Available: " << available << '\n';
return 0;
}The output setting std::boolalpha prints bool as true/false instead of 1/0.
The labels help you match each variable to its output:
Books: 7
Each: 3
Remaining: 1
Average: 3.5
Length: 12.5
Whole length: 12
Shelf: A
Available: true5. Common mistakes
Storing
3.5in anint: the fraction can be discarded. Choose a type that preserves the data you need.Writing
static_cast<double>(books / readers): integer division still happens first. Convert an operand before division, as in the example.Confusing
'A'with"A": the single quotes here make achar; double quotes make text.Assuming
unsignedor a cast fixes overflow: examine the range before calculating.
6. Practice
Change
booksto9, keepingreaders = 2. Predict the three results:4,1, and4.5.Try
length = -12.5to check that the integer part is-12, not-13.Add
<limits>and the two lines that print limits. Record your machine's result, without concluding that every machine has the same range forint.Create
const int minutesPerHour = 60;, calculate the minutes in two hours, and print120.
7. Self-check
What does
double result = 5 / 2;store? How can you obtain2.5? Answer: it stores2; use5.0 / 2or convert5todoublebefore dividing.Why should you avoid writing
int count;and immediately printingcountinsidemain? Answer: the variable has no initialized value that you can safely read. Writeint count = 0;or initialize it with the value actually needed.Does casting a very large
doubletointautomatically clamp it to the largestint? Answer: no. If its integer part is not representable, the behavior is undefined. Check the range or keep an appropriate type before converting.
Sample code
Source file
cpp98_foundation/02_types_conversions/main.cpp
#include <iostream>
int main() {
int books = 7;
const int readers = 2;
int each = books / readers;
int remaining = books % readers;
double average = static_cast<double>(books) / readers;
double length = 12.5;
int wholeLength = static_cast<int>(length);
char shelf = 'A';
bool available = true;
std::cout << "Books: " << books << '\n';
std::cout << "Each: " << each << '\n';
std::cout << "Remaining: " << remaining << '\n';
std::cout << "Average: " << average << '\n';
std::cout << "Length: " << length << '\n';
std::cout << "Whole length: " << wholeLength << '\n';
std::cout << "Shelf: " << shelf << '\n';
std::cout << std::boolalpha << "Available: " << available << '\n';
return 0;
}