Setting breakpoints and stepping through code
What you'll learn: How to pause a running C program at a specific line and execute it one step at a time to observe how data changes.
The "Freeze Ray" of Programming
Imagine you are baking a cake, but it keeps coming out salty. You can’t see what’s wrong by looking at the finished cake; you need to stop time right as you’re adding ingredients to see if you’re grabbing the salt instead of the sugar.
In C, a breakpoint is your freeze ray. It tells the debugger: "Run the program normally, but stop everything the moment you reach this specific line." Once the program is frozen, you can "step" through the code line-by-line, watching your variables change in real-time.
How to Step Through Code
Most debuggers (like GDB or the tools inside VS Code) use three main commands once you hit a breakpoint:
- Step Over: Execute the current line and move to the next one.
- Step Into: If the current line is a function call, jump inside that function to see what happens there.
- Continue: Stop pausing and let the program run normally until it hits the next breakpoint.
A Practical Example
Consider this simple loop. If your output is unexpected, you can set a breakpoint on the sum += i; line.
#include <stdio.h>
int main() {
int sum = 0;
int limit = 3;
for (int i = 1; i <= limit; i++) {
// Set a breakpoint on the line below
sum += i;
printf("Current sum: %d\n", sum);
}
return 0;
}
When the debugger hits the breakpoint, the program pauses. You can look at the "Variables" window and see that i is 1 and sum is 0. Click Step Over, and you’ll see sum instantly change to 1. Click it again, and you'll see the printf execute.
By stepping through, you aren't guessing what the computer is doing—you are watching it think. This is the most effective way to find "logical bugs," where your code compiles perfectly but produces the wrong result.
Key takeaway
Breakpoints allow you to pause your program's execution at a specific line so you can inspect variables and verify your logic one step at a time.