Debugging by printing
What you'll learn: How to use printf as a diagnostic tool to peek inside your program's memory and track its execution flow.
The "Invisible Man" problem
Code is often like an invisible man running through a house. You can hear the floorboards creak (the program runs) and see the mess he leaves behind (a crash or a wrong result), but you can’t actually see what he is doing in real-time.
When your program doesn't work, it is usually because a variable holds a value you didn't expect, or the computer is skipping a piece of code you thought would run. Debugging by printing is like throwing flour on that invisible man. By placing printf statements at critical points, you force the program to "show its work," making the invisible state of your computer visible in the console.
Where am I and what do I know?
There are two main questions a print statement can answer for you:
- The Flow: "Did my program even reach this line?"
- The State: "What is the value of my variable right at this moment?"
If your program crashes halfway through, you can place "breadcrumbs" (like printf("Reached point A\n");) to find the exact line where it dies. If your math is wrong, you can print the variables before and after a calculation to see exactly where the logic tripped.
A concrete example
Imagine you are trying to calculate a discounted price, but the result keeps coming out as zero. You can use printf to inspect the values:
#include <stdio.h>
int main() {
int price = 100;
float discount = 0.5; // 50% off
float final_price;
// Debugging: Check input values
printf("DEBUG: Price is %d, Discount is %f\n", price, discount);
final_price = price * (1 - discount);
// Debugging: Check the result
printf("DEBUG: Final price calculated as %f\n", final_price);
return 0;
}
By looking at the output, you can confirm if price was actually 100 or if it somehow changed to 0 earlier in the code.
Clean up your tracks
While debugging by printing is powerful, it is a temporary tool. Once you find the bug and fix it, remember to remove your "DEBUG" messages. Leaving them in makes your final program’s output cluttered and confusing for the actual user. Think of it like scaffolding on a building: essential during construction, but meant to be taken down once the structure is solid.
Key takeaway
Use printf to reveal hidden variable values and track which parts of your code are actually running.