Chapter 4 · Fundamental Data Types
Practice · Chapter 4

Fundamental Data Types

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.

4.3 — Object sizes and the sizeof operator

predict

Does sizeof increment x?

Predict what the two lines print. Think about whether sizeof actually runs the expression inside it.

C++
#include <iostream>

int main()
{
    int x { 1 };
    std::cout << sizeof(x++) << '\n';
    std::cout << x << '\n';
    return 0;
}
Choose the output

4.5 — Unsigned integers, and why to avoid them

predict

Is -1 less than 1u?

What does this program print? Think about how C++ finds a common type for the comparison.

C++
#include <iostream>

int main()
{
    int s { -1 };
    unsigned int u { 1 };

    if (s < u)
    {
        std::cout << "less\n";
    }
    else
    {
        std::cout << "not less\n";
    }
    return 0;
}
Choose the output

4.4 — Signed integers

fix

Fix the integer-division average

The function returns the wrong result for non-divisible inputs. Fix it so the average is computed as a true floating-point quotient.

student.cppeditable

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

4.12 — Introduction to type conversion and static_cast

write

Guard before casting to size_t

Implement isValidIndex using if statements. Check that index is nonnegative first — only then is it safe to cast it to std::size_t for the upper-bound comparison.

student.cppeditable

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

4.6 — Fixed-width integers and size_t

fix

Fix the unsigned wraparound in remaining()

The function wraps to a huge number instead of returning 0 when more items are taken than exist. Fix it so the result is clamped to zero when taken exceeds total.

student.cppeditable

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