Checking variable values with print
What you'll learn: How to inspect the current contents of your variables while a program is paused in the GDB debugger.
When you are running a program normally, it feels like a black box. Data flows in, magic happens inside, and a result comes out. If the result is wrong, you are left guessing where the logic tripped up. Using GDB is like having an X-ray machine for that box, and the print command is your primary tool for looking inside.
Peeking at the memory
Imagine you are following a complex recipe. If the cake comes out salty, you might wonder if you accidentally used salt instead of sugar. In programming, you can’t "taste" the code, but you can pause the execution and check the "jars" (your variables).
Once you have started GDB and reached a breakpoint (a spot where the code stops), the program is frozen in time. At this moment, every variable has a specific value stored in your computer's memory. To see it, you simply type print followed by the variable name.
The print command in action
Suppose you have a loop that isn't behaving as expected. You can pause the code and check the state of your counters or calculations.
#include <stdio.h>
int main() {
int total = 0;
int items = 5;
for (int i = 0; i < items; i++) {
total += i * 2; // What is 'total' right now?
}
return 0;
}
If you are paused inside that loop, you can interact with GDB like this:
- Type
print total(or justp total). - GDB will respond with something like
$1 = 6. - Type
print i. - GDB might respond with
$2 = 3.
The $1 and $2 are just GDB’s way of keeping a history of your queries. The number after the equals sign is the actual value currently sitting in that variable.
Why this matters
The print command is much faster than adding printf statements to your code, recompiling, and running it again. It allows you to verify your assumptions. If you expect a variable to be 10 but print shows it is 0, you have just found the exact moment your bug occurred. You can even print complex expressions, like print items - i, and GDB will do the math for you based on the current state of the program.
Key takeaway
Use the print command (or the shortcut p) while paused in GDB to see the live value of any variable in your program.