Turn the time you spend staring at code into time spent seeing variable values. The most practical debugging skill for beginners.
printf("x=%d\n", x);[DEBUG] for grepping later\n)// Drop printfs everywhere suspicious printf("[DEBUG] i=%d, sum=%d\n", i, sum);
for (int i = 0; i < 5; i++) { sum = sum + arr[i]; printf("[DEBUG] i=%d, arr[i]=%d, sum=%d\n", i, arr[i], sum); // β this }
int calc(int a, int b) { printf("[DEBUG] calc entry: a=%d, b=%d\n", a, b); int result = a * 2 + b; printf("[DEBUG] calc exit: result=%d\n", result); return result; }
printf("[DEBUG] before check: score=%d\n", score); if (score >= 60) { printf("[DEBUG] pass branch\n"); printf("Pass\n"); } else { printf("[DEBUG] fail branch\n"); printf("Fail\n"); }
int sum = 0; for (int i = 1; i < 10; i++) { sum = sum + i; } printf("Sum = %d\n", sum); // Output: Sum = 45 // "Wait, shouldn't it be 55?" // ...stare at code for 10 minutes... // ...still lost...
int sum = 0; for (int i = 1; i < 10; i++) { sum = sum + i; printf("[D] i=%d sum=%d\n", i, sum); } printf("Sum = %d\n", sum); // Output: // [D] i=1 sum=1 // [D] i=2 sum=3 // ... // [D] i=9 sum=45 β i stops at 9, not 10! // Sum = 45
i < 10 and i <= 10 stays fuzzy in your head, and the bug never gets fixed.| Type | Specifier | Example | Output |
|---|---|---|---|
int | %d | printf("%d", x) | 42 |
long | %ld | printf("%ld", y) | 1234567890 |
float / double | %f | printf("%.2f", z) | 3.14 |
char | %c | printf("%c", c) | A |
char[] / string | %s | printf("%s", s) | Hello |
| pointer/address | %p | printf("%p", p) | 0x7ffee... |
| hex | %x | printf("%x", n) | ff |
printf("[D] var1=%d var2=%d\n", var1, var2); everywhere and swap in the variable names. Don't forget \n (see next section).\n delays output\n (line-buffering).
printf("[D] got here"); // β no \n β nothing on screen yet! // If the program crashes after this, you'll think // "we didn't reach here" even though we did.
\n, or call fflush(stdout); right after.double x = 3.14; printf("%d\n", x); // β %d is for int; undefined value
-Wall so the compiler warns you about mismatches.[DEBUG] or [D]. Then one grep for [D] finds them all.