printf
The term "printf" is a function within the C standard library that outputs text in standard output. Standard output is typically the terminal or debug console, depending on the system a program is running on.
The "f" stands for formatted, allowing the function to output not just fixed strings, but also text that contains variable data.
"Hello, World!"
The simplest of all C programs is known as the "Hello, World!" program. It outputs "Hello, World!" using printf.
#include <stdio.h>
int main(void) {
printf("Hello world!\n");
return 0;
}
Parameter use
Parameters need to be specified in the format string. A parameter definition starts with a % character.
A simple example containing one numerical parameter looks like this:
printf("Total sum is: %d\n", Sum);
Parameter specification
Type field
The type field can be any of the following:
Character Description %
Prints a literal %
character (this type doesn't accept any flags, width, precision, or length fields).d
,i
int
as a signed decimal number.%d
and%i
produce identical output.u
Print decimal unsigned int
.f
,F
double
in normal (fixed-point) notation.x
,X
unsigned int
as a hexadecimal number.x
uses lowercase letters andX
uses uppercase.s
null-terminated string. c
char
(character).
Formatting
Formatting means replacing the parameter placeholders, such as %d or %s, with actual values. In most systems, this is done by the target. In larger systems, this is fine, but it comes at a price, as the formatting function needs handle parsing, and it needs to know all parameter types. This results in a lot of code that is used for terminal out—meaning for debugging purposes. The amount of code in this situation varies, depending on what function is supported by the formatter, but it is generally between about 3 KiB and 20 KiB.
In many IDEs, the capabilities of the formatter can be selected, so that a formatter with the required capabilities and as small a size as possible can be selected. Some IDEs, such as Rowley's Crossworks and SEGGER's Embedded Studio, also come with the ability to do host-side formatting.
With host-side or host-based formatting, the host reads the parameters and performs the formatting on itself, which eliminates the requirement to have the formatting code on the target. This is very advantageous for smaller targets, especially microcontrollers with a limited amount of program memory (Flash memory).