Chapter 10 · Type Conversion, Type Aliases, and Type Deduction
Practice · Chapter 10

Type Conversion, Type Aliases, and Type Deduction

Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.

10.5 — Arithmetic conversions

predict

What does this print?

Both variables are int. Trace the types carefully before committing to an answer.

C++
#include <iostream>

int main()
{
    int total { 7 };
    int count { 2 };
    double result = total / count;
    std::cout << result << '\n';
    return 0;
}
Choose the output

10.2 — Floating-point and integral promotion

predict

What is the size of `c`?

Both a and b are char. Think about what happens to operands before arithmetic runs.

C++
#include <iostream>

int main()
{
    char a { 10 };
    char b { 20 };
    auto c { a + b };
    std::cout << sizeof(c) << '\n';
    return 0;
}
Choose the output

10.6 — Explicit type conversion (casting) and static_cast

fix

Fix the integer-division bug in `mean`

The function should return the true mathematical average, but it always truncates. Move the static_cast to the right place.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

fix

Fix the misplaced cast in `percentage`

The static_cast is there, but it's in the wrong place. Find it and move it so the division is floating-point, not integer.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

10.3 — Numeric conversions

write

Write `safeLength` — a signed string length

Implement safeLength so callers can do signed arithmetic on the result without the unsigned-wrap trap from std::string::length().

student.cppeditable

Edit student.cpp, then Run to check it against the tests.