A format string in use
printf("element %zu is %g, \tits square is %g\n", i, A[i], A[i]*A[i]); prints literal text around three converted values. The first specifier receives i; the two %g specifiers receive the value and its square. \t and \n are escape sequences in the string literal, not format specifiers. section 1.1
A format string controls how a formatted I/O function converts values. In printf and fprintf, each conversion specifier begins with %. Trailing arguments must correspond to the conversions: the format determines both where values appear and how they are rendered. fprintf additionally takes the output stream as an argument. section 8.4.4
A printf conversion has the form %[FF][WW][.PP][LL]SS. Only the final specifier is required:
- Flags select a special form; width sets a minimum field width; precision further controls the conversion. section 8.4.4
- A modifier selects the argument type’s width. For example, z accompanies size_t in %zu, while t accompanies ptrdiff_t in %tu. section 8.4.4 section 11.1.3
- The specifier selects the conversion: %d or %u for decimal integers, %g for general floating-point output, and %x or %b for bit patterns. %% prints a percent character without converting an argument. section 8.4.4
Table 8.9 Format specifications for printf and similar functions with the general syntax "%[FF][WW][.PP][LL]SS", where [] surrounding a field denotes that it is optional
| Name | Description | |
FF |
Flags | Special form of conversion |
WW |
Field width | Minimum width |
PP |
Precision | |
LL |
Modifier | Select width of type |
SS |
Specifier | Select conversion |
Use the format-specification table to distinguish optional fields from the required conversion specifier. section 8.4.4
Input formats look similar but obey different rules. scanf, fscanf, and sscanf store converted input through pointer arguments. In a scanf format, width limits the maximum input characters rather than setting a minimum output width. Whitespace can match across newlines: scanf(" %lg %lg %lg ", &a[0], &a[1], &a[2]) is not restricted to one line. Floating-point modifiers also differ from printf; %lg is a consistent choice for double in both. section 14.2
TAKEAWAY: Keep each conversion consistent with its argument. A string literal lets modern compilers check many printf- and fprintf-style format/argument mismatches; an arbitrary char pointer can prevent that check. If a modifiable format string is changed erroneously or maliciously, the result may be an invalid format, a crash, or disclosure of secrets. For pointer output, cast the pointer to void* and use %p. section 17.2 section 11.1.3




