Loading...

C++ Casting

This page keeps the fifteen lines from the booleans page and adds three lines under them. That page ended with pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, and 0. That fifteen-line screen is the step this page builds on. The first box still holds the word pine, and the comment // the word stays pine still sits above the declarations.
This module stays on the same file. types.cpp keeps its name, its boxes, and its build command. The example adds one new box, a double named price, and three new writing lines that use it. The price box does not print anything by itself. It only holds the value 7.9 for the lines that read it. The rest of the file stays exactly the same as before, so every new line on the screen comes from the price box and the casts.
Converting one type to another is a common job. A program reads a number as text and needs it as an int, a total with cents must be shown as a whole number, or a calculation with two whole numbers must produce a fraction. Each of those jobs asks the program to change a value from one type to another, and that change is called a cast.

A cast is written with the name of the target type in angle brackets, followed by the value in parentheses. The expression static_cast(price) asks the compiler to take the double value 7.9 and produce an int. The compiler does the conversion and hands back the new value. The word static in the name means the compiler checks the cast when it builds the file, not when the program runs. If the conversion is not allowed, the build fails, and that early failure is useful.
Some conversions happen without a cast. The line double half = count; would copy the int 2 into a double box with no cast at all, because C++ quietly widens the value to 2.0. Those quiet changes are called implicit conversions. A static_cast makes the same kind of change visible on the page, so the reader sees the intent. The rule of this page is simple: when a value changes type, write the cast so the next reader knows the change was planned. Casts are most useful at the edge of a calculation, where a value enters or leaves a box of a different type.

A cast to int does not round. It drops the fraction and keeps the whole part, so 7.9 becomes 7, and 2.1 becomes 2. Rounding to the nearest whole number is a separate job, and this page does not use it. The drop always moves toward zero, which is the same rule as integer division. A cast to double does the opposite: it turns a whole number into a double, so the arithmetic that follows keeps its fraction.
This matters for division. The expression count / 4 divides two int values, because count is an int and 4 is an int. Integer division drops the fraction, so 2 / 4 gives 0. The expression static_cast(count) / 4 casts count to 2.0 first. The division now has a double on the left, so it runs in double arithmetic and gives 0.5. The box count does not change in either case. A cast reads the box, produces a new value for the expression, and leaves the box as it was. The cast returns a value and does not change the variable it read. A reader who sees the line months later can tell from the cast alone that the division was meant to keep its fraction.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Keep the fifteen lines from the booleans page. Under the bool ready line, add one new box: double price = 7.9; At the end of the writing lines, under the not line, add three lines: one for static_cast(price), one for static_cast(count) / 4, and one for static_cast(ratio * 3). The checked file is below. The file name on disk stays types.cpp.

types.cpp adds a price box and three cast lines to the fifteen

cpp
#include <iostream>
#include <string>

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    std::string other = "cone";
    std::string joined = word + " " + other;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types and then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows eighteen lines. The first fifteen are the same as on the booleans page. The sixteenth line is 7, from static_cast(price). The seventeenth is 0.5, from the double division. The eighteenth is 1, from static_cast(ratio * 3), because 1.5 turns into 1.
Check the sixteenth line first. The box price holds 7.9, and the screen shows 7, not 8. Then check the seventeenth line, which shows 0.5 and not 0. The cast is what changes that result, because without it the same count divided by 4 would show 0. The table gives each row its piece, so compare your run with it line by line. If the screen has more than eighteen lines, check that no writing line was copied twice.

📊 Three casts and what they show

Piece What the screen shows
Truncate 7, static_cast<int>(price) drops the fraction of 7.9
Divide 0.5, static_cast<double>(count) / 4 keeps the fraction
Narrow 1, static_cast<int>(ratio * 3) turns 1.5 into 1
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1

Change the price in the declaration to 9.99, then rebuild. The sixteenth line becomes 9, because the cast still drops the fraction and does not round up. Put 7.9 back. Next, change the division to static_cast(count) / 3, and the seventeenth line becomes 0.666667. cout prints six significant digits by default, so the long fraction is cut to that many digits. Put the 4 back. Last, delete the static_cast in the eighteenth line, so it reads std::cout << ratio * 3 << std::endl;. The screen now shows 1.5, because the product stays a double. Each experiment changes one thing, so the screen shows exactly which cast or number caused the difference. Put the cast back before you leave.
The next page is constants. Its job is to mark a box as fixed with the const keyword, so the compiler stops any later line that tries to change it. This page stops before const. You leave with eighteen lines on the screen, the cast results 7, 0.5, and 1, and the box price still holding 7.9. Count the lines before you leave. There are eighteen, and the last one is 1.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top