printf()

Updated: April 19, 2023

Write formatted output to stdout

Synopsis:

#include <stdio.h>

int printf( const char * format, 
            ... );

Arguments:

format
A string that controls the format of the output, as described below. The formatting string determines what additional arguments you need to provide.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The printf() function writes output to the stdout stream, under control of the argument format.

Note: If the format string contains invalid multibyte characters, processing stops, and the rest of the format string, including the % characters, is printed. This can happen, for example, if you specify international characters, accents, and diacritical marks using ISO 8859-1 instead of UTF-8. If you call:
setlocale( LC_CTYPE, "C-TRADITIONAL" );

before calling printf(), the locale switches multibyte processing from UTF-8 to 1-to-1, and printf() safely transfers the misformed multibyte characters.

Format Arguments

If there are leftover arguments after processing format, they're ignored.

(QNX Neutrino 7.1 or later) Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence %n$, where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages; see “Examples,” below.

The format can contain either numbered argument conversion specifications (that is, %n$ and *m$), or unnumbered argument conversion specifications (that is, % and *), but not both. The only exception to this is that %% can be mixed with the %n$ form. The results of mixing numbered and unnumbered argument specifications in a format string are undefined. When numbered argument specifications are used, specifying the nth argument requires that all the leading arguments, from the first to the (n - 1)th, be specified in the format string.

In format strings containing the %n$ form of conversion specification, numbered arguments in the argument list can be referenced from the format string as many times as required.

In format strings containing the % form of conversion specification, each conversion specification uses the first unused argument in the argument list.

The printf() family of functions allows for language-dependent radix characters. The default character is “.”, but is controlled by LC_NUMERIC and setlocale().

Format control string

The format control string consists of:

multibyte characters
These are copied to the output stream exactly as they occur in the format string. An ordinary character in the format string is any character, other than a percent character (%), that isn't part of a conversion specifier.
conversion specifiers
These cause argument values to be written as they're encountered during the processing of the format string. A conversion specifier is a sequence of characters in the format string that begins with % or %n$ and is followed by:
  • zero or more format control flags that can modify the final effect of the format directive
  • an optional decimal integer, or an asterisk (*), that specifies a minimum field width to be reserved for the formatted item
  • an optional precision specification in the form of a period (.), followed by an optional decimal integer or an asterisk (*)
  • an optional type length specification, one of: h, hh, j, l, ll, L, t or z
  • a character that specifies the type of conversion to be performed. See below.
Note: The <inttypes.h> header file defines some PRI* macros that expand to the conversion specifiers for various data types.

Format control flags

The valid format control flags are:

-
Left-justify the formatted item within the field; normally, items are right-justified.
+
Always start a signed, positive object with a plus character (+); normally, only negative items begin with a sign.
space
Always start a signed, positive object with a space character; if both + and a space are specified, + overrides the space.
#
Use an alternate conversion form:
  • For o (unsigned octal) conversions, increment the precision, if necessary, so that the first digit is 0.
  • For x or X (unsigned hexadecimal) conversions, prepend a nonzero value with 0x or 0X.
  • For e, E, f, g, or G (any floating-point) conversions, always include a decimal-point character in the result, even if no digits follow it; normally, a decimal-point character appears in the result only if there is a digit to follow it.
  • In addition, for g or G conversions, don't remove trailing zeros from the result.
0 (zero)
Use leading zeros to pad the field width for d, i, o, u, x, X, e, E, f, g and G conversions. The - flag overrides the this flag.

Field width

If you don't specify a field width, or if the given value is less than the number of characters in the converted value (subject to any precision value), a field of sufficient width to contain the converted value is used.

If the converted value has fewer characters than specified by the field width, the value is padded on the left (or right, subject to the left-justification flag) with spaces or zero characters (0). If the field width begins with a zero, the value is padded with zeros; otherwise, the value is padded with spaces.

If the field width is * (or 0*), a value of type int from the argument list is used (before a precision argument or a conversion argument) as the minimum field width. A negative field width value is interpreted as a left-justification flag, followed by a positive field width.

In format strings containing the %n$ form of a conversion specification, a field width or precision may be indicated by the sequence *m$, where m is a decimal integer in the range [1,{NL_ARGMAX}] giving the position in the argument list (after the format argument) of an integer argument containing the field width or precision, for example:

printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);

Precision specifier

As with the field width specifier, a precision specifier of * causes a value of type int from the argument list to be used as the precision specifier.

The precision value affects the following conversions:

Type length specifier

A type length specifier affects the conversion as follows:

Conversion type specifiers

The valid conversion type specifiers are:

a, A
Convert an argument of type double in the style [-]0xh.hhhh p1d, where there's one nonzero hexadecimal digit before the decimal point. The number of hexadecimal digits after the decimal point is equal to the precision. If the precision is missing and FLT_RADIX is a power of 2, then the precision is sufficient for an exact representation. If the precision is zero and you don't specify the # flag, no decimal point is shown.

The a conversion uses the letters abcdef and produces x and p; the A conversion ABCDEF, X and P. The exponent always has one digit, even if it's 0, and no more digits than necessary. The values for infinity or NaN are converted in the style of an f or F.

c
Convert an argument of type int into a value of type unsigned char and write the corresponding ASCII character code to the output stream.

An l (“el”) qualifier causes a wint_t argument to be converted as if by an ls conversion into a wchar_t, the first element being the wint_t and the second being a null wide character.

d, i
Convert an argument of type int into a signed decimal notation and write it to the output stream. The default precision is 1, but if more digits are required, leading zeros are added.
e, E
Convert an argument of type double into a decimal notation in the form [-]d.ddde[+|-]dd. The leading sign appears (subject to the format control flags) only if the argument is negative.

If the argument is nonzero, the digit before the decimal-point character is nonzero. The precision is used as the number of digits following the decimal-point character. If you don't specify the precision, a default precision of six is used. If the precision is 0, the decimal-point character is suppressed. The value is rounded to the appropriate number of digits.

The exponent sign and the exponent (that indicates the power of ten by which the decimal fraction is multiplied) are always produced. The exponent is at least two digits long and has only as many additional digits as necessary to represent it. If the value is zero, the exponent is zero.

For E conversions, the exponent begins with the character E, rather than e.

The arguments infinity or NaN are converted in the style of the f or F conversion specifiers.

f, F
Convert an argument of type double into a decimal notation in the form [-]ddd.ddd with the number of digits after the decimal point being equal to the precision specification. The leading sign appears (subject to the format control flags) only if the argument is negative.

The precision is used as the number of digits following the decimal-point character. If you don't specify the precision, a default precision of six is used. If the precision is 0, the decimal-point character is suppressed; otherwise, at least one digit is produced before the decimal-point character. The value is rounded to the appropriate number of digits.

An argument of type double that represents infinity or NaN is converted to [-]inf or [-]nan. The F specifier produces [-]INF or [-]NAN.

g, G
Convert an argument of type double using either the e or f (or E, for a G conversion) style of conversion, depending on the value of the argument. In either case, the precision specifies the number of significant digits that are contained in the result. The e style conversion is used only if the exponent from such a conversion would be less than -4 or greater than the precision. Trailing zeros are removed from the result, and a decimal-point character only appears if it is followed by a digit.

Arguments representing infinity or NaN are converted in the style of the f or F conversion specifiers.

n
Assign the number of characters that have been written to the output stream to the integer pointed to by the argument. No output is produced.
o
Convert an argument of type unsigned into an unsigned octal notation, and write it to the output stream. The default precision is 1, but if more digits are required, leading zeros are added.
p
Convert an argument of type void * into a value of type int, and format the value as for a hexadecimal (x) conversion, except that p doesn't support the alternate conversion form (#).
s
Write the characters from the string specified by an argument of type char *, up to, but not including the terminating NUL character ('\0'), to the output stream. If you specify a precision, no more than that many characters are written.

If you use an l (“el”) qualifier, the argument is interpreted as a pointer to a wchar_t array, and each wide character, including the terminating NUL, is converted as if by a call to wcrtomb(). The terminating NUL is written only if you don't specify the precision, or if you specify the precision and the length of the character sequence is less than the precision.

u
Convert an argument of type unsigned into an unsigned decimal notation, and write it to the output stream. The default precision is 1, but if more digits are required, leading zeros are added.
x, X
Convert an argument of type unsigned into an unsigned hexadecimal notation, and write it to the output stream. The default precision is 1, but if more digits are required, leading zeros are added.

Hexadecimal notation uses the digits 0 through 9 and the characters a through f or A through F for x or X conversions, respectively, as the hexadecimal digits. Subject to the alternate-form control flag, 0x or 0X is prepended to the output.

%
Print a % character (the entire specification is %%).

Any other conversion type specifier character, including another percent character (%), is written to the output stream with no special interpretation.

The arguments must correspond with the conversion type specifiers, left to right in the string; otherwise, indeterminate results will occur.

If the value corresponding to a floating-point specifier is infinity, or not a number (NaN), then the output will be inf or -inf for infinity, and nan or -nan for NaNs.

For example, a specifier of the form %8.*f defines a field to be at least 8 characters wide, and gets the next argument for the precision to be used in the conversion.

Returns:

The number of characters written, excluding the terminating NUL, or a negative number if an error occurred (errno is set).

Examples:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char *weekday, *month;

    weekday = "Saturday";
    month = "April";
    printf( "%s, %s %d, %d\n", weekday, month, 10, 1999 );
    printf( "f1 = %8.4f f2 = %10.2E x = %#08x i = %d\n",
             23.45, 3141.5926, 0x1db, -1 );
    return EXIT_SUCCESS;
}

produces the output:

Saturday, April 10, 1999
f1 =  23.4500 f2 =  3.14E+003 x = 0x0001db i = -1

You can use the following statement to print the date and time using a language-independent format:

printf(format, weekday, month, day, hour, min);

For US usage, format could be a pointer to the string "%s, %s %d, %d:%.2d\n", which results in a message in the following format:

Sunday, July 3, 10:02

For German usage, format could be a pointer to the string "%1$s, %3$d. %2$s, %4$d:%5$.2d\n", which results in a message in the following format:

Sonntag, 3. Juli, 10:02

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes