Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 135 ยท Getting Started

Printing Output with printf

Master printf in C - common format specifiers (%d, %zu, %f, %s, %p, %x), width, precision and flags, puts and putchar, escapes and format warnings.

Almost every program you write in this course shows its results with printf, the standard library's formatted print function. You give it a format string, text with placeholders in it, followed by the values that fill those placeholders. printf turns each value into text according to its placeholder and writes the result to standard output, which in our editor is the output panel.

printf is powerful but unforgiving: each placeholder must match the type of its value, or the output is garbage (or worse). This lesson teaches the format specifiers you'll use daily, how to control width, precision and alignment, the simpler puts and putchar, escape sequences, and how the compiler helps you catch mistakes.

How printf works

A call to printf looks like this:

C
printf("format string", value1, value2, ...);

printf copies the format string to the output character by character. When it meets a %, it reads a conversion specification such as %d, takes the next value from the argument list, converts it, and prints the result. The number of values must match the number of specifications.

C Format specifiers fill placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is:

TEXT
7 apples at 0.450000 each
Grade: A
Bought at Corner Market
Total: 3.15
100% fresh

Notice that %f prints six digits after the decimal point by default, %.2f prints two, and %% prints a single percent sign. printf adds nothing on its own, not even a line break, so each format string ends with \n.

The common format specifiers

Specifier Type of the value Example output
%d or %i int (signed decimal) -42
%u unsigned int 42
%ld, %lu long, unsigned long 1234567890
%lld, %llu long long, unsigned long long 9000000000
%zu size_t (sizes, sizeof results) 8
%hhd, %hd signed char, short (rarely needed) -5
%f double (fixed notation) 3.141593
%e double (scientific notation) 3.141593e+00
%g double (shorter of %f/%e, no trailing zeros) 3.14159
%Lf long double 3.141593
%c a character (int/char) A
%s a string (char *, null-terminated) hello
%p a pointer (void *) 0x7ffd4c2a1b3c
%x, %X unsigned int in hexadecimal ff, FF
%o unsigned int in octal 377
%% no value; prints % %

The letters before the conversion character (l, ll, z, h, hh, L) are length modifiers: they tell printf how big the argument is. For float, use %f too: a float passed to printf is automatically converted to double.

Here they are in action. The %p line prints a memory address that changes from run to run:

C Integers, floats, characters and pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A few things to notice:

  • 3000000000u doesn't fit in a signed int, but it fits in an unsigned int (up to 4,294,967,295 on our system), so %u prints it correctly.
  • %g drops trailing zeros and switches to scientific notation for very large or small numbers: 1.5e+20.
  • 'z' printed with %d shows its character code, 122. Characters are small integers in C; Characters and ASCII explains why.
  • %p expects a void *, so the address is cast with (void *). You'll understand addresses in Pointers.

Note: size_t is the unsigned type that sizeof and strlen return. Its size differs between platforms, so always print it with %zu, never %d. Fixed-width types like int64_t have their own macros in <inttypes.h>; see Integer Types.

Width, precision and flags

Between the % and the conversion character you can add more instructions, in this order:

TEXT
%[flags][width][.precision][length]conversion
  • Width is the minimum number of characters to print. Shorter values are padded with spaces on the left (right-aligned).
  • Precision (after a dot) means digits after the decimal point for %f and %e, significant digits for %g, the maximum number of characters for %s, and the minimum number of digits for integers.
  • Flags change the padding and signs:
Flag Effect Example Output
- left-align within the width "[%-6d]", 42 [42 ]
0 pad numbers with zeros "%05d", 42 00042
+ always show a sign "%+d", 42 +42
space space where a + would go "% d", 42 42
# alternate form: 0x prefix for hex, 0 for octal "%#x", 255 0xff

Width and precision are perfect for tables:

C Aligned columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The table lines up because every row uses the same widths: %-10s left-aligns the name in 10 characters, %5d right-aligns the quantity in 5, and %9.2f right-aligns the price in 9 with 2 decimals. Below the table:

TEXT
[   3.142]  [3.1     ]  [00003.14]
[+5] [-5] [ 5]
[Tru]
[0007]  [0xff]  [010]
[          99]
[2.8]

An asterisk (%*d, %.*f) takes the width or precision from an extra int argument placed before the value, which is useful when the width is computed at run time.

Tip: %.2f rounds to two decimals, but it rounds the number as it's actually stored in binary. 2.675 is stored as slightly less than 2.675, so printf("%.2f", 2.675) prints 2.67, not 2.68. For money, many programs store whole cents in an integer and format it themselves. Floating-Point Numbers explains why.

Escape sequences

Inside a string, a backslash starts an escape sequence, a way to write characters you can't type directly:

Escape Meaning
\n new line
\t horizontal tab
\\ a backslash
\" a double quote
\' a single quote
\r carriage return (cursor to start of line)
\0 the null character (ends a string)
\a, \b alert (beep), backspace
\x41, \101 character by hex or octal code (both are A)
C Escape sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Note the difference between \", which is handled by the compiler when it reads the string, and %%, which is handled by printf when it runs. A literal percent sign is just a normal character to the compiler, but printf treats it as the start of a specification.

puts and putchar

For simple output, two smaller functions are handy:

  • puts(s) prints the string s followed by a newline. It does no formatting, so % has no special meaning.
  • putchar(c) prints a single character.
C puts and putchar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The loop prints abcde one character at a time. The last two lines show that printf returns the number of characters it wrote, 7 here (Hello! plus the newline), or a negative number if output failed. Most programs ignore that value, but it's there when you need it.

Warning: Never pass text you didn't write as the format string: printf(user_text); treats any % in it as a specification, which prints garbage or crashes, and is a well-known security hole. Write printf("%s", user_text); or puts(user_text); instead. GCC warns format not a string literal and no format arguments.

Mismatched specifiers

The compiler can't stop you from passing the wrong type to printf, because printf accepts any number of arguments of any type (it's a variadic function). If the specifier and the value don't match, the behavior is undefined: you might see a nonsense number, a different number on another computer, or a crash.

Luckily GCC and Clang check format strings against the arguments when the format is a literal. This example compiles with warnings on purpose:

C The compiler checks your formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC prints a warning for every line, such as format '%d' expects argument of type 'int', but argument 2 has type 'double' and format '%d' expects a matching 'int' argument. The numbers the program prints are meaningless and can differ between runs and systems, so don't read anything into them. Fix each specifier (%f, %d, %zu, and add the missing value) and the warnings disappear. For the size_t line GCC suggests %ld, because size_t happens to be unsigned long on our Linux server; %zu is the portable choice that is correct everywhere.

Output buffering and stderr

printf doesn't always send text to the screen immediately. Standard output is usually buffered: text collects in memory and is written in chunks, at the end of a line when output goes to a terminal, or when the buffer fills or the program ends otherwise. If a program crashes, text still in the buffer can be lost. Call fflush(stdout); to force it out.

For error messages, C provides a second output stream, standard error (stderr), which is unbuffered. Write to it with fprintf, which takes the stream as its first argument:

C
fprintf(stderr, "Error: could not open %s\n", filename);

Keeping errors separate lets users redirect normal output to a file while still seeing errors. In our editor, both streams appear in the output panel. You'll use fprintf with files in File Handling Basics.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf("[%5d]", 42); print?

    A width of 5 pads the number to five characters. Numbers are right-aligned by default, so three spaces come first.
  2. 2. Which specifier should you use for a value returned by sizeof?

    sizeof returns size_t, an unsigned type whose size depends on the platform. %zu always matches it.
  3. 3. What does printf("%.1f|%-4d|%%", 2.25, 7); print?

    %.1f rounds to one decimal (2.25 is stored as exactly 2.25 and rounds to even, giving 2.2), %-4d left-aligns 7 in four characters, and %% prints one percent sign.
  4. 4. How many characters does printf("Hi!\n") return?

    printf returns the number of characters written: H, i, ! and the newline make 4.
  5. 5. Why is printf(name); dangerous when name comes from the user?

    The user's text becomes the format string, so sequences like %s or %n make printf read arguments that don't exist. Use printf("%s", name) or puts(name).

Summary

  • printf(format, values...) replaces each % specification with the next value, converted to text.
  • Match each specifier to its type: %d int, %u unsigned, %ld/%lld long/long long, %zu size_t, %f/%e/%g double, %c char, %s string, %p pointer, %x hex, %% a percent sign.
  • Width, precision and flags (-, 0, +, space, #, *) control alignment, decimals and padding.
  • Escape sequences like \n, \t, \\ and \" put special characters in strings.
  • puts prints a string plus a newline; putchar prints one character; printf returns the number of characters written.
  • Mismatched specifiers are undefined behavior: keep -Wall on and fix every format warning. Never use untrusted text as a format string.

Next: Reading Input with scanf and fgets, where your programs start reading what the user types.