typestar

printf conversions in C

The format string is a small language: width, precision, and the right specifier per type.

#include <stdio.h>

void formats(void) {
    int count = 42;
    double rate = 91.5;
    const char *name = "typestar";
    size_t size = sizeof(count);

    printf("%d %5d %-5d|\n", count, count, count);
    printf("%.2f %8.3f %e\n", rate, rate, rate);
    printf("%s %10s %-10s|\n", name, name, name);
    printf("%zu bytes, %c, %x, %o\n", size, 'A', 255, 8);
    printf("%p\n", (void *) name);
    printf("%%d prints a literal percent\n");
}

How it works

  1. %d is int, %u unsigned, %zu size_t, %p a pointer.
  2. %-8s left-aligns in eight columns, %.2f fixes the decimals.
  3. A mismatched specifier is undefined behavior, not a warning you may ignore.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
404
Tokens
119
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 1 of 2 in Input & output, step 31 of 35 in Language basics.

← Previous Next →