The Art in Code

Snippets of famous, interesting, historically relevant or thought-provoking... code.


Website maintained by Filip Stanis Based on theme by mattgraham

006 - printf

Code snippet of the printf function

Snippet source

“printf” is the name of one of the most well known and most used functions in the C programming language.

It stands for “print formatted” and it’s used to display output on the screen in a formatted way, by using a simple structured template language.

Equivalent or similar functions exist in many other programming languages.

Example use

For example, to display two numbers with a dash in between, printf could be used this way:

printf("%d-%d", first_number, second_number);

In this example, %d is the template used to indicate a number (the “d” stands for “decimal”). printf replaces this with the number provided in the arguments.

Importance

Because displaying text on screen is a very easy way to see the effect of running a program, printf is often the first function introduced when learning how to code.

The function name also became well known over the years and is sometimes used to refer to the general idea of displaying things on the screen. For example, the term “printf debugging” is used to denote using printf statements to track the flow of execution when debugging code.

Snippet explanation

The snippet above comes from glibc and is just a trivial wrapper around vfprintf which implements the logic behind printf.

The wrapper exists because printf is a variadic function while the less-known vfprintf is not and also allows specifying the output location, while printf sends the output to stdout.