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 anywhere that looks 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; }
if branchesprintf("[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 that be 55?" // ...stare at the 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.%d and %f).char, strings, pointers, and hex are covered in their own later lessons (Strings, Pointers, Bitwise, and so on). For now, int β %d, double β %f is all you need.
| Type | Specifier | Example | Output |
|---|---|---|---|
int β
use now | %d | printf("%d", x) | 42 |
float / double β
use now | %f | printf("%.2f", z) | 3.14 |
long | %ld | printf("%ld", y) | 1234567890 |
char later | %c | printf("%c", c) | A |
char[] / string later | %s | printf("%s", s) | Hello |
| pointer/address later | %p | printf("%p", p) | 0x7ffee... |
| hex later | %x | printf("%x", n) | ff |
printf("[D] var1=%d var2=%d\n", var1, var2); wherever you need it and swap in your variable names. Don't forget the \n (see the next section).\n delays your outputprintf buffers its output for efficiency and only flushes on a newline \n (line buffering).
printf("[D] got here"); // β no \n β nothing shows up on screen yet! // If the program crashes after this line, you'll conclude // "we never reached this point" β even though we did.
\n, or call fflush(stdout); right after.double x = 3.14; printf("%d\n", x); // β %d is for int β undefined behavior
-Wall so the compiler warns you about mismatches.[DEBUG] or [D]. Then a single grep for [D] finds them all.Check your understanding of this lesson!
int variable in decimal?%d is for decimal integers, %f is for floating-point, and %s is for strings.
\n is a newline, \t is a tab, and \\ is a literal backslash.
%p formats a void * as hexadecimal safely. Using %d is implementation-defined and unsafe.