Chapter 3 · Debugging C++ Programs
Practice · Chapter 3

Debugging C++ Programs

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.

3.5 — More debugging tactics

predict

What does this program print?

The program is compiled without -DDEBUG_MODE. Read carefully — what appears on standard output?

C++
#include <iostream>

int compute(int x)
{
#ifdef DEBUG_MODE
    std::cerr << "input: " << x << '\n';
#endif
    return x * 2;
}

int main()
{
    int result { compute(5) };
    std::cout << result << '\n';
    return 0;
}
Choose the output

3.1 — Syntax and semantic errors

predict

Logical error: what does this print?

The function is named area and called with width=4, height=5. What does the program print?

C++
#include <iostream>

int area(int width, int height)
{
    return width + height;  // computes area of a 4x5 rectangle
}

int main()
{
    std::cout << area(4, 5) << '\n';
    return 0;
}
Choose the output

3.2 — The debugging process

fix

Fix the wrong coin constant

The function converts a collection of coins to total cents. One constant is wrong — find and change that single token.

student.cppeditable

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

fix

Fix the subtracted dimension

The function should return the perimeter of a rectangle. One arithmetic operator is wrong — change that single token.

student.cppeditable

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

3.3 — A strategy for debugging

write

Implement the height conversion

Implement toTotalInches(feet, extraInches): return the total number of inches. There are 12 inches in one foot.

student.cppeditable

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