Codiqo

Learn C · lesson 4 of 60 · about 7 minutes

Format Specifiers and Comments

Tell printf how to show each value with %d, %f, %c, %s and %%, and explain your code with comments.

What you'll learn

  • Choose the right format specifier
  • Control decimal places with %.2f
  • Write // and /* */ comments

A placeholder for every type

Bytes in memory don't say what they mean: the same bytes could be a whole number, a letter or part of a decimal. So printf needs you to say how to show each value, and the specifier must match the type:

| Specifier | Prints | Example value |
|---|---|---|
| %d | int | 42 |
| %f | double (6 decimals) | 2.500000 |
| %.1f | double, 1 decimal | 2.5 |
| %c | one character | 'C' |
| %s | text (a string) | "ada" |
| %% | a percent sign | |

Different specifiers

#include <stdio.h>

int main(void) {
    double mib = 2.5;
    char drive = 'C';
    printf("Size: %f\n", mib);
    printf("Size: %.1f MiB\n", mib);
    printf("Drive: %c\n", drive);
    printf("User: %s\n", "ada");
    printf("Disk: 31%%\n");
    return 0;
}

Output

Size: 2.500000
Size: 2.5 MiB
Drive: C
User: ada
Disk: 31%

When the specifier is wrong

printf trusts you completely. Give %d a double and it reads the double's bytes as if they were an int, and prints nonsense: a big random-looking number, different each run. Nothing crashes, so this kind of bug is easy to miss.

When a number looks impossible, check that every specifier matches its value.

Comments

Comments are notes for humans; the compiler ignores them. // turns the rest of a line into a comment, and /* ... */ can cover several lines.

Comments don't change the output

#include <stdio.h>

/* System report.
   Run it to see how full the disk is. */
int main(void) {
    // printf("Debug: starting\n");
    printf("Report ready\n"); // shown to the user
    return 0;
}

Output

Report ready

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.