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
What does this program print?
The program is compiled without -DDEBUG_MODE. Read carefully — what appears on standard output?
#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;
}3.1 — Syntax and semantic errors
Logical error: what does this print?
The function is named area and called with width=4, height=5. What does the program print?
#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;
}3.2 — The debugging process
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.
Edit student.cpp, then Run to check it against the tests.
Fix the subtracted dimension
The function should return the perimeter of a rectangle. One arithmetic operator is wrong — change that single token.
Edit student.cpp, then Run to check it against the tests.
3.3 — A strategy for debugging
Implement the height conversion
Implement toTotalInches(feet, extraInches): return the total number of inches. There are 12 inches in one foot.
Edit student.cpp, then Run to check it against the tests.