Lesson 186 +10 XP

Debugging

Debugging is the process of finding and fixing errors in your program. A systematic approach beats staring at the code for hours, and the tools in your IDE can show you exactly what the program is doing.

The debugging process

A simple process that works: find the bug, narrow the scope, and reproduce the circumstances around it.

Code

cpp
int main() {
    double x = 10.0;
    double y = 0.0;
    cout << "x / y = " << x / y;
}

Enter a zero for y and you get a weird value. The first debugging step is to make the problem happen again, then inspect the values that flow through the calculation.

Printing values as a quick check

The oldest and simplest trick: print intermediate values, then remove them later.

Code

cpp
int main() {
    int sum = 0;
    for (int i = 1; i < 5; i++) {
        sum += i;
        cout << "sum after " << i << " = " << sum;   // debug print
    }
}

A quick cout next to a statement lets you see whether each step produces the number you expected. Remove those lines before you ship.

Breakpoints: pausing at a line

A breakpoint tells the debugger &quot;stop right here&quot;. When the run reaches the marked line, the program pauses and waits for you.

Stepping: run one step at a time

Once paused, you control the execution:

  • Step into dives into a function call and runs it line by line.
  • Step over runs the whole function call without going inside.
  • Continue keeps running until the next breakpoint.

Watch window and call stack

While paused, a watch window shows the value of a named variable. The call stack is the list of active functions at that moment, in order. Together they answer &quot;what is this variable right now?&quot; and &quot;how did the program get here?&quot;

TL;DR

  • Debugging is the process of finding and fixing errors.
  • Use printing to inspect intermediate values quickly.
  • A breakpoint stops the program at a chosen line.
  • Step into dives in, step over hops a function, continue resumes.
  • A watch shows a value; the call stack shows how you arrived.