Skip to the workspace
Pebellslearn by building
Variables  ›  Lesson

Printing Variables

Printing Variables 12 minprintf builds text from a format string in which every conversion specifier must be matched, left to right, by an argument of the right type.

c / Printing Variables

Explore each scene at your own pace.

01 · The rule

The rule

Printing Variables

printf builds text from a format string in which every conversion specifier must be matched, left to right, by an argument of the right type.

Match formatted output placeholders to argument types and inspect the printed result.

At the end of each day the logger prints a summary line: how many readings, the average, the unit. printf builds that line from a template and a list of values. It is fast and flexible, but it trusts you completely: it cannot see the types of your values, so if the template and the values disagree, the output is garbage or worse.

The rule

Every % in printf needs one matching value of the matching type.

The first argument is the format string. Each conversion specifier, starting with %, is replaced by the next argument, left to right:

int count = 3;
double avg = 21.466;
char unit = 'C';

printf("%d readings, average %.1f %c\n", count, avg, unit);
/* prints: 3 readings, average 21.5 C */

The specifiers you will use most:

Specifier Type Example output
%d int 42
%u unsigned int 42
%ld / %lld long / long long 5256000
%zu size_t (from sizeof) 96
%f double (a float is promoted to double) 21.466000
%c a character C
%s a string ready
%x unsigned int in hexadecimal 2a
%% a literal percent sign %

Between % and the letter you can add a width and a precision:

  • %5d pads the number to at least 5 characters, right-aligned; %-5d left-aligns.
  • %.1f shows one digit after the decimal point, rounding the value.
  • %8.2f does both.

If a specifier does not match its argument's type, for example %d given a double, the behaviour is undefined. -Wall turns on GCC's and Clang's format checks, which catch most mismatches at compile time.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.