Chapter 12 · Compound Types: References and Pointers
Practice · Chapter 12

Compound Types: References and Pointers

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.

12.3 — Lvalue references

predict

What does assigning through a reference actually do?

Trace each variable carefully after ref = y executes, then pick the output.

C++
#include <iostream>

int main()
{
    int x { 1 };
    int y { 2 };

    int& ref { x };
    ref = y;

    std::cout << x << ' ' << y << '\n';
}
Choose the output

12.14 — Type deduction with pointers, references, and const

predict

Does `auto` preserve `const`?

Predict what prints — pay close attention to what auto deduces.

C++
#include <iostream>

int main()
{
    const int x { 42 };
    auto y { x };

    y = 99;

    std::cout << x << ' ' << y << '\n';
}
Choose the output

12.10 — Pass by address

fix

Fix the swap-by-pointer function

The function is supposed to swap the two ints the pointers point at, but it leaves them unchanged. Find the bug and fix it.

student.cppeditable

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

12.15 — std::optional

write

Write `findFirst` using `std::optional`

Implement findFirst so it returns the index of the first occurrence of target in text, or std::nullopt if not found.

student.cppeditable

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

12.13 — In and out parameters

write

Write two in/out parameter functions

Implement scale and clampToZero — both take a non-const reference as an in/out parameter and modify the caller's variable directly.

student.cppeditable

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