This loop goes round more than a hundred times. Typing next and print n each time would take all day.
display, until and advance
Level 10 of 13 · interactive GDB exercise · runs in your browser
Keep an eye on values while stepping through a loop, and run to a later line without setting a breakpoint.
display n shows n after every stop. Pressing Enter on an empty line repeats your last command.
When you have seen enough, until 13 runs until line 13 is next. No breakpoint needed.
Watch n for a few trips round the loop, then jump straight to the return.
You work in a real GDB session on the program below. A breakpoint on collatz_steps was set and the program was started; it is paused at the first line of collatz_steps.
#include <stdio.h>
int collatz_steps(int n) {
int steps = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps++;
}
return steps;
}
int main(void) {
int steps = collatz_steps(27);
printf("27 takes %d steps\n", steps);
return 0;
}
main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.
display <expr>undisplay [n](Enter)until [where]advance <where>tbreak <where>nextfinishprint <expr>until with no line in the middle of the loop and seeing it behave like next. Plain until only refuses to jump back up at the end of a loop body. Give it a line: until 13.undisplay removes all displays; undisplay 2 removes one. info display shows the numbers.advance or until with a line the program never reaches. It also stops when the current function returns, so you end up in the caller. Type run to start again.