← C++ from Scratch
Lesson 48 of 62 · 10 XP
Debugging
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Debugging is looking for where the program behaves differently from what you think.
- Reproduce the error on a small example.
- Narrow down the place: debug output
std::cerr << "i=" << i << " sum=" << sum << '\n';—std::cerrgoes to a separate error stream and doesn't get in the way of the real output. - Check your assumptions:
assert(n > 0);from<cassert>stops the program if the condition is false, and tells you where. - On your own computer there's a debugger (
gdb,lldb, the debugger in an IDE): breakpoints, step-by-step execution, viewing variables.-gat compile time adds debugging information, and-fsanitize=address,undefinedcatches going out of bounds and UB right at the moment of the error.
Usual suspects: loop bounds (< or <=), uninitialised variables, integer division,
= instead of ==, a forgotten break in a switch.
Task. The program has three errors. It should read n and n numbers and print the average
with two decimal places and the count of numbers greater than the average. Find and fix the errors (you can use debug std::cerr).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.