Formatted output and format contracts
Match output conversions to argument types, distinguish width from precision, and check bounded formatting and stream failures.
In this chapter7 sections
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 conversion | Required value |
|---|---|
%d, %i | int, decimal |
%u, %x | unsigned int, decimal / hexadecimal |
%ld, %lld | long / long long |
%zu | size_t |
%f, %e, %g | double; float is promoted to double |
%Lf | long double |
%c | int after the required promotions |
%s | Readable character sequence; normally null terminated |
%p | void *; 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.
#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.
#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
#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
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
- WG14 N1570 — public C11 committee draft: 6.5.2.2, 7.8.1, 7.21.6.1, 7.21.6.3, 7.21.6.5. Stable core provisions used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 7.23.6.1. C23 notes are source-reviewed separately from C17 example checks.
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.
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.
Read the explanation for every choice
- Only how many characters the output should look like.
Appearance does not establish a valid argument type for a conversion.
- Only the variable’s name.
Identifier spelling does not communicate the argument’s required type.
- 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:
| Specifier | printf / fprintf argument | scanf / fscanf destination |
|---|---|---|
| %d | int, decimal output | int *, decimal input |
| %i | int, decimal output | int *, base-detecting input (decimal/octal/hex in C17) |
| %u | unsigned int, decimal output | unsigned int *, unsigned decimal conversion |
| %f / %e | double (float is promoted to double) | float * |
| %lf / %le | double; l does not change these output conversions | double * |
| %Lf / %Le | long double | long double * |
| %c | int after integer promotions, printed as a character | char *; no null terminator, no leading-whitespace skip |
| %s | Pointer to a null-terminated character string | char array with enough space; use a field width |
| %x / %X | unsigned int, hexadecimal output | unsigned int *, hexadecimal input |
| %p | void *; e.g. printf("%p", (void *)p) | void **; implementation-defined pointer text |
| %% | Print a literal percent; no argument | Match 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.