C Programming/Procedures and functions/printf

From Wikibooks, open books for an open world
Jump to navigation Jump to search

About the printf Function[edit | edit source]

In C, the printf function prints the optional arguments under the control of the template string template to the stream stdout. It returns the number of characters printed, or a negative value if an output error occurred.

int printf (const char *template, ...)

For more information about printf in general, see the Wikipedia article on printf.

Output Conversions[edit | edit source]

Here is a table summarizing what all the different conversions do in the C implementation of printf:

`%d', `%i'
Print an integer as a signed decimal number. `%d' and `%i' are synonymous for output, but are different when used with scanf() function for input.
`%o'
Print an integer as an unsigned octal number.
`%u'
Print an integer as an unsigned decimal number.
`%x', `%X'
Print an integer as an unsigned hexadecimal number. `%x' uses lower-case letters and `%X' uses upper-case.
`%f'
Print a floating-point number in normal (fixed-point) notation.
`%e', `%E'
Print a floating-point number in exponential notation. `%e' uses lower-case letters and `%E' uses upper-case.
`%g', `%G'
Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. `%g' uses lower-case letters and `%G' uses upper-case.
`%a', `%A'
Print a floating-point number in a hexadecimal fractional notation which the exponent to base 2 represented in decimal digits. `%a' uses lower-case letters and `%A' uses upper-case.
`%c'
Print a single character.
`%lc'
Print a single wide character.
`%C'
This is an alias for `%lc'. (This is a non-standard Unix-specific extension.)
`%s'
Print a string.
`%ls'
Print a wide character string.
`%S'
This is an alias for `%ls'. (This is a non-standard Unix-specific extension.)
`%p'
Print the value of a pointer.
`%n'
Get the number of characters printed so far. Note that this conversion specification never produces any output.
`%m'
Print the string corresponding to the value of errno variable. (This is a non-standard GNU extension.)
`%%'
Print a literal `%' character.

If the syntax of a conversion specification is invalid, unpredictable things will happen, so don't do this. If there aren't enough function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are unpredictable. If you supply more arguments than conversion specifications, the extra argument values are simply ignored; this is sometimes useful.