Watch and print
- C course
- Intermediate
- Lesson 96/116
- 5 min
Learn to watch and print variables in gdb.
print and watch
In gdb, print expr shows the current value of any expression. For example print counter gives the variable's value, print arr[2] the third array element.
watch var stops the program whenever that variable changes. This is ideal for catching bugs where a variable changes unexpectedly. Set watch counter and gdb stops each time counter is updated, showing the old and new values. print gives a snapshot, watch gives continuous monitoring. Using both, you can trace a variable's entire life story.
The accumulation pattern
Tracking how a variable changes over time makes the accumulation pattern useful. You update a counter variable through a loop and print the result at the end.
Example: int counter = 0; for (int i = 0; i < 5; i++) counter += i;. After the loop counter is 0+1+2+3+4 = 10. In gdb, set watch counter to see how the value grows at each step. This is the basis of statistical calculations like sum, average, or maximum. Use print counter to check the current value each time you stop.
Practice Write an accumulation program
Declare int counter = 0;. Loop with for (int i = 0; i < 5; i++) and do counter += i;. After the loop print the result with printf("toplam=%d\n", counter);.
Starter code
#include <stdio.h>
// Define counter as 0
// Loop from 0 to 4 and add to counter
// Print with "toplam=%d\n"
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int counter = 0;
for (int i = 0; i < 5; i++) {
counter += i;
}
printf("toplam=%d\n", counter);
return 0;
}Expected output
toplam=10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the accumulation
counter += ____;
counter += i;
Explanation: counter += i; adds the value of i at each iteration.
2 Match the inspection commands
| Term | Meaning |
|---|---|
print x |
Current value |
watch x |
Stop on change |
display x |
Show every step |
info locals |
All locals |
3 What does the watch command do?
- Deletes the variable
- Stops when the variable changes Correct answer
- Restarts the program
- Shows source code
Explanation: watch stops the program whenever the variable changes.