Stepping through code with next and step
What you'll learn: How to move through your program line-by-line using GDB to observe how your code executes in real-time.
Once you have set a breakpoint and started your program with run, your code will pause at a specific line. Now, you need to move forward. Think of GDB like a remote control for a movie: you can play frame-by-frame to see exactly where a "visual effect" (or in our case, a bug) goes wrong.
The next command (n)
The next command tells GDB to execute the current line and stop at the very next line of the current function.
Imagine you are reading a recipe. If the step says "Preheat the oven," you do that and then look at the next instruction. You don't need to know the physics of how the oven heats up; you just want to get to the next step of the recipe. In programming, if a line calls a function—like printf()—next will run that entire function and stop right after it.
The step command (s)
The step command is more surgical. If the current line contains a function call that you wrote, step will "dive inside" that function so you can follow the logic there.
Using the recipe analogy, if the instruction says "Make the secret sauce," and you use step, you are now looking at a separate page that explains how to mix the mayo, mustard, and spices. You are no longer on the main recipe; you are stepping into the details.
Seeing it in action
Consider this simple program:
#include <stdio.h>
void greet() {
printf("Hello there!\n");
}
int main() {
int x = 10;
greet(); // Line A
x = 20; // Line B
return 0;
}
If your program is paused at Line A:
- Typing
next(or justn) will execute thegreet()function entirely and move the pointer directly to Line B. - Typing
step(or justs) will jump the debugger into thegreet()function, allowing you to walk through theprintfcall before returning tomain.
Use next when you trust a function works and just want to stay in your current flow. Use step when you suspect the bug is hiding inside a function call.
Key takeaway
Use next to skip over function details and step to dive into them for a closer look.