Printing Variables
printf builds text from a format string in which every conversion specifier must be matched, left to right, by an argument of the right type.
Match formatted output placeholders to argument types and inspect the printed result.
At the end of each day the logger prints a summary line: how many readings, the average, the unit. printf builds that line from a template and a list of values. It is fast and flexible, but it trusts you completely: it cannot see the types of your values, so if the template and the values disagree, the output is garbage or worse.
The rule
Every % in printf needs one matching value of the matching type.
The first argument is the format string. Each conversion specifier, starting with %, is replaced by the next argument, left to right:
int count = 3;
double avg = 21.466;
char unit = 'C';
printf("%d readings, average %.1f %c\n", count, avg, unit);
/* prints: 3 readings, average 21.5 C */The specifiers you will use most:
| Specifier | Type | Example output |
|---|---|---|
%d |
int |
42 |
%u |
unsigned int |
42 |
%ld / %lld |
long / long long |
5256000 |
%zu |
size_t (from sizeof) |
96 |
%f |
double (a float is promoted to double) |
21.466000 |
%c |
a character | C |
%s |
a string | ready |
%x |
unsigned int in hexadecimal |
2a |
%% |
a literal percent sign | % |
Between % and the letter you can add a width and a precision:
%5dpads the number to at least 5 characters, right-aligned;%-5dleft-aligns.%.1fshows one digit after the decimal point, rounding the value.%8.2fdoes both.
If a specifier does not match its argument's type, for example %d given a double, the behaviour is undefined. -Wall turns on GCC's and Clang's format checks, which catch most mismatches at compile time.