7.4 — Printing to find bugs
Read one box at a time. No rush.
Add print lines#
The simplest debugging tool: print what's happening.
C++
int total { 0 };for (int i { 1 }; i <= 3; ++i){ total += i * 2; std::cerr << "i=" << i << " total=" << total << '\n'; // debug line}Output
i=1 total=2i=2 total=6i=3 total=12Now you can see each step and spot where it goes wrong.
Tip
Use std::cerr for debug lines instead of std::cout. It prints straight away (nothing gets stuck), and it's easy to find and remove later.
Narrow it down#
- Print a value at the start. Is it right?
- Print it in the middle. Still right?
- Print it at the end. Wrong now?
The bug is between the last "right" and the first "wrong". Keep halving the gap.
Clean up#
Remove your debug prints when you're done. Or comment them out with // if you think you'll need them again.
Tip: press ← / → to move between lessons, / to search.