Previous Page
Next Page

printf

Writes formatted output to the standard output stream

#include <stdio.h>
int printf ( const char * restrict format , ... );

The printf( ) function converts various kinds of data into string representations for output, and substitutes them for placeholders in the string referenced by the mandatory pointer argument, format. The resulting output string is then written to the standard output stream. The return value of printf( ) is the number of characters printed, or EOF to indicate that an error occurred.

The placeholders in the string argument are called conversion specifications, because they also specify how each replacement data item is to be converted, according to a protocol described shortly.

The optional arguments, represented by the ellipsis in the function prototype, are the data items to be converted for insertion in the output string. The arguments are in the same order as the conversion specifications in the format string.

Conversion specification syntax

For a general overview of data output with printf( ), see "Formatted Output" in Chapter 13. This section describes the syntax of conversion specifications in the printf( ) format string in detail. The conversion specifications have the following syntax:

%[flags][field width][.precision][length modifier]specifier

The flags consist of one or more of the characters +, ' ' (space), -, or 0. Their meanings are as follows:


+

Add a plus sign before positive numbers.


' '

Add a space before positive numbers (not applicable in conjunction with +).


-

Align the output with the left end of the field.


0

Pad the field with leading zeroes to the left of the numeric output (not applicable in conjunction with -). Ignored for integer types if precision is specified.


#

Use alternative conversion rules for the following conversion specifiers:


A, a, E, e, F, f, G, g

Format floating-point numbers with a decimal point, even if no digits follow.


G, g

Do not truncate trailing zeroes.


X, x, o

Format nonzero hexadecimal integers with the 0X or 0x prefix; format octal integers with the 0 prefix.

The optional field width is a positive integer that specifies the minimum number of characters that the given data item occupies in the output string. If the flags include a minus sign, then the converted argument value is aligned left in the field; otherwise, it is aligned right. The remaining field width is padded with spaces (or zeroes, if the flags include 0). If the converted data item is longer than the specified field width, it is inserted in the output string in its entirety.

If an asterisk (*) appears in place of the field width, then the argument to be converted for output must be preceded by an additional argument with the type int, which indicates the field width for the converted output.

For the conversion specifiers f, F, e, E, a, and A, precision specifies the number of decimal places to present. For the conversion specifier g, precision indicates the number of significant digits. The result is rounded. The default value for precision is 6.

For integersthat is, the conversion specifiers u, d, i, x, and o--precision specifies a minimum number of digits to present. The converted value is padded with leading zeroes if necessary. The default value for precision in this case is 1. If you convert a zero integer value with zero precision, the result is no characters.

For the conversion specifier s, indicating a string argument, precision specifies the maximum length of the string to be inserted in the output.

If an asterisk (*) appears in place of a precision value, then the argument to be converted for output must be preceded by an additional argument with the type int, which indicates the precision for the converted output. If asterisks appear both for field width and for precision, then the argument to be converted must be preceded by two additional int arguments, the first for field width and the second for precision.

The length modifier qualifies the conversion specifier to indicate the corresponding argument's type more specifically. Each length modifier value is applicable only to certain conversion specifier values. If they are mismatched, the function's behavior is undefined. The permissible length modifier values and their meaning for the appropriate conversion specifiers are listed in Table 17-5.

Table 17-5. printf( ) conversion specifier modifiers

Modifier

With conversion specifier

Corresponding argument's type

hh

d, i, o, u, x, or X

signed char or unsigned char

hh

n

signed char *

h

d, i, o, u, x, or X

short int or unsigned short int

h

n

short int *

l (ell)

d, i, o, u, x, or X

long int or unsigned long int

l (ell)

c

wint_t

l (ell)

n

long int *

l (ell)

s

wchar_t *

l (ell)

a, A, e, E, f, F, g, or G

(The modifier is permitted, but has no effect)

ll (two ells)

d, i, o, u, x, or X

long long or unsigned long long

ll (two ells)

n

long long *

j

d, i, o, u, x, or X

intmax_t or uintmax_t

j

n

intmax_t *

z

d, i, o, u, x, or X

size_t or the corresponding signed integer type

z

n

size_t * or a pointer to the corresponding signed integer type

t

d, i, o, u, x, or X

ptrdiff_t or the corresponding unsigned integer type

t

n

ptrdiff_t * or a pointer to the corresponding unsigned integer type

L

a, A, e, E, f, F, g, or G

long double


The conversion specifier indicates the type of the argument and how it is to be converted. The corresponding function argument must have a compatible type; otherwise, the behavior of printf( ) is undefined. The conversion specifier values are listed in Table 17-6.

Table 17-6. printf( ) conversion specifiers

Conversion specifier

Argument type

Output notation

d, i

int

Decimal

u

unsigned int

Decimal

o

unsigned int

Octal

x, X

unsigned int

Hexadecimal

f, F

float or double

Floating decimal point

e, E

float or double

Exponential notation

g, G

float or double

Floating decimal point or exponential notation, whichever is shorter

a, A

float or double

Hexadecimal exponential notation

c

char or int

Single character

s

char *

The string addressed by the pointer argument

n

int *

No output; instead, printf( ) stores the number of characters in the output string so far in the variable addressed by the argument

p

Any pointer type

The pointer value, in hexadecimal notation

%

None

A percent sign (%)


The exact meaning of the a and A conversion specifiers, introduced in C99, is somewhat complicated. They convert a floating-point argument into an exponential notation in which the significant digits are hexadecimal, preceded by the 0x (or 0X) prefix, and with one digit to the left of the decimal point character. The exponential multiplier, separated from the significant digits by a p (or P), is represented as a decimal exponent to base FLT_RADIX. The symbolic constant FLT_RADIX, defined in float.h, indicates the base of the floating-point environment's exponent representation; this is usually 2, for binary exponent representation. Here is an example using the a conversion specifier:

double pi = 3.1415926;
double bignumber = 8 * 8 * 8 * pi * pi * pi;
printf("256 times pi cubed equals %.2e, or %.2a.\n", bignumber, bignumber);

This printf( ) call produces the following output:

256 times pi cubed equals 1.59e+04, or 0x1.f0p+13.

The first representation of p shown here, produced by the e conversion specifier, reads "one point five nine times ten to the fourth power," and the second, produced by a, as "hexadecimal one point F zero times two to the (decimal) thirteenth power."

For floating-point arguments, and for the x or X conversion specifiers, the case of the conversion specifier determines the case of any letters in the resulting output: the x (or X) in the hexadecimal prefix; the hexadecimal digits greater than 9; the e (or E) in exponential notation; infinity (or INFINITY) and nan (or NAN); and p (or P) in hexadecimal exponential notation.

In Chapter 2, we described the types with specific characteristics defined in stdint.h, such as intmax_t for the given implementation's largest integer type, int_fast32_t for its fastest integer type of at least 32 bits, and the like (see Table 2-5). The header file stdint.h also defines macros for the corresponding conversion specifiers for use in the printf( ) functions. These conversion specifier macros are listed in Table 17-7.

Table 17-7. Conversion specifier macros for integer types defined in stdint.h

Type

Meaning

printf( ) conversion specifiers

intN_t

uintN_t

An integer type whose width is exactly N bits

PRIdN, PRIiN

PRIoN, PRIuN, PRIxN, PRIXN

int_leastN_t

uint_leastN_t

An integer type whose width is at least N bits

PRIdLEASTN, PRIiLEASTN

PRIoLEASTN, PRIuLEASTN, PRIxLEASTN, PRIXLEASTN

int_fastN_t

uint_fastN_t

The fastest type to process whose width is at least N bits

PRIdFASTN, PRIiFASTN

PRIoFASTN, PRIuFASTN, PRIxFASTN, PRIXFASTN

intmax_t

uintmax_t

The widest integer type implemented

PRIdMAX, PRIiMAX

PRIoMAX, PRIuMAX, PRIxMAX, PRIXMAX

intptr_t

uintptr_t

An integer type wide enough to store the value of a pointer

PRIdPTR, PRIiPTR

PRIoPTR, PRIuPTR, PRIxPTR, PRIXPTR


The macros in Table 17-7 expand to string literals. Therefore, when you use one in a printf( ) format string, you must close the quotation marks surrounding the format string on either side of the macro. Here is an example:

int_fast16_t counter = 1001;
while ( --counter )
  printf( "Only %" PRIiFAST16 " nights to go.\n", counter );

The preprocessor expands the macro and concatenates the resulting string literal with the adjacent ones on either side of it.

Example

The following example illustrates the use of the %n conversion specification to count the characters in the output string:

void print_line( double x)
{
  int n1, n2;
  printf("x = %5.2f   exp(x) = %n%10.5f%n\n", x, &n1, exp(x), &n2);
  assert( n2-n1 <= 10);     // Did printf( ) stretch the field width?
}

int main( )
{
  print_line( 11.22);
  return 0;
}

The code produces the following output:

x = 11.22   exp(x) = 74607.77476
printf_ex: printf_ex.c:20: print_line: Assertion `n2-n1 <= 10' failed.
Aborted

See Also

The other functions in the "printf( ) family," fprintf( ), sprintf( ), and snprintf( ); the printf( ) functions for wide characters (declared in wchar.h): wprintf( ), fwprintf( ), and swprintf( ); the printf( ) functions that use the type va_list for the variable arguments (declared in stdarg.h): vprintf( ), vfprintf( ), vsprintf( ), and vsnprintf( ); the printf( ) functions for wide characters that use the type va_list for the variable arguments, vwprintf( ), vfwprintf( ), and vswprintf( ); the formatted input functions scanf( ), sscanf( ), and fscanf( )


Previous Page
Next Page