Thuta Learning
C
BasicProgrammingBeginner

Output

CLesson 425 min

What you'll walk away with

  • Print values of the right type with %d, %f, %c, %s, %zu and %%
  • Control where lines end with the escape sequences \n, \t, \" and \\
  • Line up columns with widths and precision such as %5d, %-8s and %.2f
  • Explain and prevent format/type mismatches and format-string bugs

Explain it simply

Explain it simply

printf() is how a C program talks to you on the console. You give it a sentence with blanks in it, the format string, followed by the values that fill the blanks in order. %d marks a blank for a whole number, %f one for a decimal number and %s one for text. Two-character codes called escape sequences put invisible things into the text: \n moves to a new line.

It works a bit like a form letter: the template is written once and the details are slotted in when you send it. The one rule to remember is that printf trusts you completely about which kind of value fills each blank.

Problem → Why → Solution

The problem: a receipt that compiles, runs and prints nonsense

This receipt program compiles and runs. The first line is right. The second prints a meaningless number instead of 12.5, and the third prints a second number nobody passed: one test run printed Total: 0 and Paid: 3 of 1, and another machine may show different numbers. Thank you! has no newline, so it runs straight into the terminal's prompt.

With -Wall, GCC warns about lines 5 and 6: "format '%d' expects argument of type 'int', but argument 2 has type 'double'" and "format '%d' expects a matching 'int' argument". With warnings off, it says nothing.

receipt.c
#include <stdio.h>

int main(void) {
    printf("Items: %d\n", 3);
    printf("Total: %d\n", 12.5);      /* %d, but 12.5 is a double */
    printf("Paid: %d of %d\n", 3);    /* two %d, only one value */
    printf("Thank you!");             /* no newline at the end */
    return 0;
}

Why can't printf catch this itself?

printf is a variadic function: it accepts any number of arguments of any type and learns their types only by reading the format string at run time. If the format says int and you pass a double, printf reads the wrong bits from the wrong place, which is undefined behavior. The compiler can check a format written as a string literal, but only when warnings are on.

Core concept: the format string is a contract

printf walks through the format string from left to right. Ordinary characters are copied out unchanged; each % starts a conversion specification that takes the next argument and turns it into text. So the first specifier pairs with the first argument, the second with the second, and the number of specifiers must match the number of arguments.

SpecifierArgument typeExample output
%dint42
%f, %.2fdouble (a float arrives converted to double)3.141590, 3.14
%cchar (passed as an int)A
%sstring (a char array)hello
%zusize_t (what sizeof and strlen return)5
%lldlong long9000000000
%%Takes no argument%

Two details explain the type column. When a float or a char is passed to printf, C first converts it, a float to double and a char to int, under rules called the default argument promotions. That is why %f prints both float and double, and why %lf means the same as %f in printf (the difference matters only for scanf). Larger types need a length modifier in front of the letter: l for long, ll for long long and z for size_t.

Between the % and the letter you can add flags, a width and a precision. %5d reserves at least five columns and right-aligns the number, %-8s left-aligns because of the - flag, %.2f rounds to two digits after the decimal point, and %8.2f combines both. A width is only a minimum: a longer value is never cut, it just widens the column.

Escape sequences are a separate mechanism. The compiler turns \n, \t, \" and \\ into single characters while it builds the string literal, so by the time printf sees them they are a real newline, tab, quote and backslash. The % specifiers, by contrast, are handled by printf itself at run time, which is why a literal percent sign is written %%.

text
How specifiers pair with arguments
----------------------------------
printf("%-8s|%5d|%8.2f\n", "Tea", 2, 1.5);
        ^^^^ ^^^ ^^^^^     ^^^^^  ^  ^^^
        1    2   3         1      2  3   <- spec N takes argument N

prints:  Tea     |    2|    1.50
         <---8--> <-5-> <---8-->
Mental model: printf fills in a template
  1. printf scans the format left to right
  2. Plain characters are copied as-is
  3. Each % spec takes the next argument
  4. The spec, not the value, picks the type

Count the arguments and pair them with the specifiers; if they do not match, printf will not fix it for you.

General pattern

c
printf("plain text\n");
printf("%d %f %c %s\n", int_value, double_value, char_value, "text");
printf("[%5d] [%-8s] [%8.2f]\n", number, word, amount);   /* width, precision */
printf("100%%\n");                                         /* a literal percent */
puts("puts adds the newline for you");
fprintf(stderr, "error: %s\n", message);                   /* the error stream */

Each specifier is followed by one argument of the matching type. The width controls the column size and the precision the number of decimals. puts is the simple choice for fixed text, and fprintf(stderr, ...) sends error messages to a separate stream.

Example: separate lines and an aligned table

The first three lines show how newlines put each message on its own line. A small table then uses widths and precision to line prices up, and the last line collects the escape sequences and %%.

output.c
#include <stdio.h>

int main(void) {
    printf("Hello World!\n");
    printf("I am learning C.\n");
    printf("C is fast and powerful.\n");

    printf("%-8s|%5s|%8s\n", "Item", "Qty", "Price");
    printf("%-8s|%5d|%8.2f\n", "Tea", 2, 1.5);
    printf("%-8s|%5d|%8.2f\n", "Noodles", 1, 3.25);
    printf("Quote: \"C\"  Backslash: \\  Percent: 100%%\n");
    return 0;
}

Code breakdown

  1. Lines 4-6printf("C is fast and powerful.\n");

    All three lines end with \n. Without it on the last one, the shell prompt would appear glued to the end of the text.

  2. Line 8printf("%-8s|%5s|%8s\n", "Item", "Qty", "Price");

    The header row. %-8s left-aligns Item in eight columns, while %5s and %8s right-align Qty and Price so they sit above the numbers below.

  3. Line 9printf("%-8s|%5d|%8.2f\n", "Tea", 2, 1.5);

    Arguments pair up in order: the string goes to %-8s, the int 2 to %5d and the double 1.5 to %8.2f. The .2 makes 1.5 print as 1.50.

  4. Line 10printf("%-8s|%5d|%8.2f\n", "Noodles", 1, 3.25);

    Reusing the same format string gives every row the same columns. Noodles has seven characters, so one space pads it to eight.

  5. Line 11printf("Quote: \"C\" Backslash: \\ Percent: 100%%\n");

    \" puts a double quote inside the string without ending it, and \\ prints one backslash. %% is turned into a single percent sign by printf.

You should see
Hello World!
I am learning C.
C is fast and powerful.
Item    |  Qty|   Price
Tea     |    2|    1.50
Noodles |    1|    3.25
Quote: "C"  Backslash: \  Percent: 100%

puts, fputs and putchar

Fixed text with no values to fill in does not need printf. puts(text) prints the text and adds a newline for you. fputs(text, stdout) adds no newline, so you can build a line in pieces, and putchar writes a single character. None of them treat % specially. printf itself returns the number of characters it printed (or a negative value on error), which programs that must be sure their output arrived can check.

puts_demo.c
#include <stdio.h>

int main(void) {
    puts("puts adds the newline for you");
    fputs("fputs does not, ", stdout);
    fputs("so lines can be built in pieces\n", stdout);
    putchar('O');
    putchar('K');
    putchar('\n');
    return 0;
}

stdout, stderr and buffering

printf writes to standard output (stdout). For error messages, write to standard error with fprintf(stderr, ...). When you redirect output to a file with ./report > out.txt, only the stdout line lands in the file; the stderr line still appears on screen, so the user sees the error.

Output is not always written immediately; it can wait in a buffer. The C standard says stdout is fully buffered when it can be determined not to refer to an interactive device, and on terminals most implementations flush at each newline. stderr, by contrast, starts out not fully buffered. That is why, in a pipe, a stderr line can show up before an earlier stdout line. Call fflush(stdout) when text must appear right away.

streams.c
#include <stdio.h>

int main(void) {
    printf("Report: 3 files checked\n");
    fprintf(stderr, "warning: config.txt not found, using defaults\n");
    return 0;
}

In real projects

How this shows up in real projects

Command-line tools use printf widths and precision all the time: the neatly aligned columns of file listings, process tables and benchmark reports come from specifiers like these. Programs send normal output to stdout and diagnostics to stderr, so scripts can pipe the data onward while people still see the errors. On embedded systems, many toolchains can route printf to a serial port, which lets developers debug boards that have no screen at all.

The same format language is reused in many places: fprintf writes to files, snprintf formats into a memory buffer, and scanf uses similar specifiers to read input. Format-string bugs have been a real class of security vulnerabilities, so many build setups add -Wformat-security and code reviews check that user-supplied text never ends up in the format position.

Common mistakes

Common mistakes

1. A specifier that does not match the type

printf("%d\n", 12.5); is undefined behavior and may print any number. size_t is another trap: printing a strlen result with %d makes the Windows GCC used for this lesson warn that "argument 2 has type 'size_t' {aka 'long long unsigned int'}". Use %d for int, %f for double, %zu for size_t and %lld for long long, and keep -Wall on.

2. Pressing Enter inside a string

A string literal cannot run over two lines: press Enter inside the quotes and GCC reports the error missing terminating " character, followed by a cascade of other errors. Write \n where you want a line break in the output. To split long text in the source, write two adjacent literals such as "Hello, " "world"; the compiler joins them into one.

3. Passing user text as the format

printf(name); seems fine until name contains a % such as "100%sure"; then printf tries to read an argument that does not exist. -Wall -Wextra do not catch it; -Wformat-security (or -Wformat=2) warns "format not a string literal and no format arguments". Write printf("%s", name) or fputs(name, stdout) instead.

4. Expecting %.2f to round decimal digits exactly

%.2f rounds the binary value stored in memory, not the decimal digits you typed. 2.675 is stored as something close to 2.67499..., so it prints 2.67, and 1.005 prints 1.00. Programs that need exact cents usually store money as whole numbers of cents.

Mini challenge

Mini challenge: an aligned receipt

Print a small receipt whose columns line up and whose total C computes for you.

  • A header row with Item (left-aligned in 10 columns), Qty (right-aligned in 4) and Cost (right-aligned in 8)
  • Rows for 2 x Rice at 1.20 and 12 x Eggs at 0.25, with each cost computed in the argument and shown with %8.2f
  • A Total row whose number lines up under the Cost column
  • A last line with a literal percent sign: Tax: 0% (included)
receipt.c
#include <stdio.h>

int main(void) {
    // TODO: header row: "Item" left-aligned in 10 columns,
    //       "Qty" right-aligned in 4, "Cost" right-aligned in 8

    // TODO: a row for 2 x Rice at 1.20 each; compute the cost in the
    //       printf argument and show it with two decimals

    // TODO: a row for 12 x Eggs at 0.25 each

    // TODO: a Total row whose number ends under the Cost column

    // TODO: print Tax: 0% (included)  (how do you print a % sign?)

    return 0;
}

Expected: These five lines, with the columns aligned: Item Qty Cost Rice 2 2.40 Eggs 12 3.00 Total 5.40 Tax: 0% (included)

Show hint

Use the same widths (10, 4, 8) in the header and item rows. On the Total row, one specifier of width 4 + 8 = 12 covers both the Qty and Cost columns.

Show solution
receipt.c
#include <stdio.h>

int main(void) {
    printf("%-10s%4s%8s\n", "Item", "Qty", "Cost");
    printf("%-10s%4d%8.2f\n", "Rice", 2, 2 * 1.20);
    printf("%-10s%4d%8.2f\n", "Eggs", 12, 12 * 0.25);
    printf("%-10s%12.2f\n", "Total", 2 * 1.20 + 12 * 0.25);
    printf("Tax: 0%% (included)\n");
    return 0;
}

Quick quiz 1 / 3

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

Quick quiz 2 / 3

Which call prints a size_t value n correctly?

Quick quiz 3 / 3

A program reads a user's name into name and calls printf(name);. Why is this risky?

What to remember

  • printf reads the format left to right and pairs each % specifier with the next argument in order.
  • The specifier must match the type: %d for int, %f for double, %c for char, %s for strings, %zu for size_t.
  • Escape sequences such as \n are converted by the compiler; specifiers such as %% are handled by printf at run time.
  • Widths and precision such as %5d, %-8s and %.2f line columns up.
  • Never pass user text as the format: use printf("%s", text) and keep -Wall on.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Output | Thuta Learning