YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 50 of 73

Formatted output and format contracts

Match output conversions to argument types, distinguish width from precision, and check bounded formatting and stream failures.

6 min readIntermediateC17 baseline
Offline reading
In this chapter7 sections
0% through this chapter

Formatted output combines data with instructions about how to display it. The format string must agree with the supplied argument types. We will read that agreement carefully, then handle storage limits and output failures.

1. A format specifies an argument contract

printf writes to stdout, fprintf to a chosen stream, and snprintf to a bounded character array. A format string contains ordinary text and conversions beginning with %. Their requirements are part of the call’s correctness. %% prints a percent sign without consuming a value argument.

Output conversionRequired value
%d, %iint, decimal
%u, %xunsigned int, decimal / hexadecimal
%ld, %lldlong / long long
%zusize_t
%f, %e, %gdouble; float is promoted to double
%Lflong double
%cint after the required promotions
%sReadable character sequence; normally null terminated
%pvoid *; use an appropriate object-pointer cast

Variadic calls apply default argument promotions, so float becomes double and eligible small integer types undergo integer promotion. They do not infer a size_t format from %d. Use the matching format or an explicitly justified value conversion. With <inttypes.h>, the PRI macros provide formats for the corresponding integer typedefs when available. Pointer formatting is implementation-defined and does not portably print function pointers.

Complete C17 program
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int score = 73;
    size_t count = 3;
    float ratio = 0.5f;
    int written = printf("score=%d count=%zu ratio=%.1f\n", score, count, ratio);
    if (written < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

2. Width and precision control presentation

A width such as %8d requests a minimum field width; a larger result is not truncated to fit eight characters. Precision has conversion-specific meaning: %.2f requests two fractional digits, %.4d requests a minimum number of integer digits, and %.3s limits the bytes printed from a character sequence. A * width or precision consumes an int argument. None of these output rules is interchangeable with scanf’s input field width.

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char label[3] = { 'C', 'A', 'T' };
    if (printf("%.3s\n", label) < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

The three-element array has no terminating null character. This particular precision keeps the conversion within the three valid elements. Plain %s would instead require a terminating null character within accessible storage. For runtime lengths, verify that an int precision can represent the length before converting it; a negative precision is treated as omitted, not as a zero-length safety bound.

3. Keep external data out of the format language

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char *message = "progress: 100%";
    if (printf("%s\n", message) < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

The fixed "%s\n" is the format; the message is data. Passing externally supplied text as printf(message) can interpret percent sequences as conversion instructions, with missing arguments or writes through %n. Use a fixed format or fputs for plain text. A trusted string’s percent sign needs no escaping when passed as a %s value.

4. Bounded output still needs a result check

C17 · illustrative fragment
char label[5];
int needed = snprintf(label, sizeof label, "%s", "Codedile");
bool failed = needed < 0;
bool truncated = !failed && (size_t)needed >= sizeof label;

This fragment uses <stdio.h> and <stdbool.h>. For positive capacity, snprintf writes at most capacity minus one characters and terminates the result. Its nonnegative return is the number of characters that would have been written with enough space, excluding the terminator. First handle a negative error result; only then convert to size_t and compare with capacity. A value at least capacity means truncation, even though the stored prefix is terminated.

The source and destination must still meet their pointer and overlap contracts; snprintf is not permission to copy overlapping strings. A successful formatting call also does not make buffered stream output durable. printf/fprintf report a negative result on an output or encoding error, and a later fflush or fclose can still report a failure.

Primary references and further reading

The later variadic-functions chapter explains why the argument types behind a format string need an explicit agreement.

Before you move on

  • Formats must match the supplied argument types after the relevant promotions.
  • Width, precision, and destination capacity solve different formatting questions.
  • Output errors and truncation must be checked under the chosen function’s rules.
Keep these ideas separate
Bounded output / Complete output
A capacity-limited write can still fail or truncate; its return result determines what was provided.
Explain it in your own words

What would you check after snprintf before treating its buffer as the complete requested message?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

What must a printf conversion agree with?
Read the explanation for every choice
  1. Only how many characters the output should look like.

    Appearance does not establish a valid argument type for a conversion.

  2. Only the variable’s name.

    Identifier spelling does not communicate the argument’s required type.

  3. The actual argument type after the applicable argument promotions.

    ✓ Correct reasoning. The format string is a contract; it does not generally convert a mismatched argument into the required type.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.

Standard Streams

A hosted C program starts with stdin, stdout, and stderr already open. Initially stderr is not fully buffered; it is commonly unbuffered, but the standard does not require that exact buffering mode. Interactive standard input/output is commonly line-buffered; buffering depends on the stream and environment.

Formatted I/O

printf and scanf — and their file-oriented siblings fprintf/fscanf — use a format string containing conversion specifiers:

Specifierprintf / fprintf argumentscanf / fscanf destination
%dint, decimal outputint *, decimal input
%iint, decimal outputint *, base-detecting input (decimal/octal/hex in C17)
%uunsigned int, decimal outputunsigned int *, unsigned decimal conversion
%f / %edouble (float is promoted to double)float *
%lf / %ledouble; l does not change these output conversionsdouble *
%Lf / %Lelong doublelong double *
%cint after integer promotions, printed as a characterchar *; no null terminator, no leading-whitespace skip
%sPointer to a null-terminated character stringchar array with enough space; use a field width
%x / %Xunsigned int, hexadecimal outputunsigned int *, hexadecimal input
%pvoid *; e.g. printf("%p", (void *)p)void **; implementation-defined pointer text
%%Print a literal percent; no argumentMatch a literal percent; no destination

Length modifiers must match the actual types: %ld uses long for output and long * for input; %zu uses size_t and size_t *. For char word[20], scanf("%19s", word) reserves space for the terminating null character; check that its return value is 1 before using the result. Check the expected assignment count for other input calls too. For robust numeric input, prefer fgets followed by a conversion such as strtol, checking the end pointer, ERANGE, and the destination type's range: an out-of-range scanf numeric conversion is undefined behavior, not merely a failed match. Output functions can also fail; a negative printf return indicates an error.

Buffering

Buffered output need not appear immediately. Line-buffered output commonly flushes at a newline, and fully buffered output accumulates until a buffer fills or is flushed. Use fflush(stdout) when a prompt must be sent before input, and check errors when output matters. Normal exit flushes open output streams, but abnormal termination need not. In portable C, fflush(stdin) is not an input-clearing operation; applying fflush to an input stream has undefined behavior.

Character and Line I/O

getchar returns an int: either an unsigned char value converted to int, or EOF. Store it in int and test for EOF before converting to a character; feof/ferror distinguish end-of-file from an input error. For n > 1, fgets(s, n, stream) reads at most n - 1 characters, retains a newline if read, and appends a null character on success. Provide space for n characters and check the return value. Success does not guarantee a complete line or exclude input null characters. puts appends a newline; fputs does not. gets was removed in C11.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 50 / 73

In this chapter

Formatted output and format contracts

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping