7.4 — Printing to find bugs

📘 Chapter 7⏱ about 1 min read✍️ Beginner friendly
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=12

Now 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#

  1. Print a value at the start. Is it right?
  2. Print it in the middle. Still right?
  3. 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.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.