All Topics  
Printf

 

   Email Print
   Bookmark   Link






 

Printf



 
 
The class of printf functions (which stands for "print formatted") is a class of functions, typically associated with curly bracket programming language
Curly bracket programming language

Curly brace or bracket programming languages are those which use balanced brackets to make block s in their syntax or formal grammar, mainly due to being C -influenced....
s, that accept a string
String (computer science)

In computer programming and some branches of mathematics, a string is an ordered sequence of symbols. These symbols are chosen from a predetermined set or alphabet....
 parameter
Parameter (computer science)

In computer programming, a parameter is a special kind of variable#In_computer_programming that refers to data that a subroutine receives to operate on....
 (called the format string) which specifies a method for rendering a number of other parameters (of which there typically may be arbitrarily many, of a variety of types
Data type

A data type in programming languages is an attribute of a data which tells the computer something about the kind of data it is. This involves setting constraints on the datum, such as what values it can take and what operations may be performed upon it....
) into a string. Usually this string is then printed on the standard output stream, but variants exist that perform other tasks with the result.






Discussion
Ask a question about 'Printf'
Start a new discussion about 'Printf'
Answer questions from other users
Full Discussion Forum



Encyclopedia


The class of printf functions (which stands for "print formatted") is a class of functions, typically associated with curly bracket programming language
Curly bracket programming language

Curly brace or bracket programming languages are those which use balanced brackets to make block s in their syntax or formal grammar, mainly due to being C -influenced....
s, that accept a string
String (computer science)

In computer programming and some branches of mathematics, a string is an ordered sequence of symbols. These symbols are chosen from a predetermined set or alphabet....
 parameter
Parameter (computer science)

In computer programming, a parameter is a special kind of variable#In_computer_programming that refers to data that a subroutine receives to operate on....
 (called the format string) which specifies a method for rendering a number of other parameters (of which there typically may be arbitrarily many, of a variety of types
Data type

A data type in programming languages is an attribute of a data which tells the computer something about the kind of data it is. This involves setting constraints on the datum, such as what values it can take and what operations may be performed upon it....
) into a string. Usually this string is then printed on the standard output stream, but variants exist that perform other tasks with the result. Characters in the format string are usually copied literally into the function's output, with the other parameters being rendered into the resulting text at points marked by format specifiers, which are typically introduced by a % character
Percent sign

The percent sign is the symbol used to indicate a percentage . It is represented in Unicode by .Related signs include the permille sign ? and the permyriad sign , which indicate that a number is divided by one thousand or ten thousand respectively....
. A literal percent sign can be copied into the output using the escape sequence
Escape sequence

An escape sequence is a series of character used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control....
 %%.

Timeline

Several programming languages implement a printf function
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
, to output a formatted string
String literal

A string literal is the representation of a String value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the individual programming language in question....
. It originated from the C programming language
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
, where it has a prototype
Function prototype

A function prototype in C or C++ is a declaration of a subroutine that omits the function body but does specify the function's name, arity, argument datatypes and return type....
 similar to the following: int printf(const char *format, ...) The string constant
Variable

A variable is a symbol that stands for a value that may vary; the term usually occurs in opposition to constant, which is a symbol for a non-varying value, i.e....
 format provides a description of the output, with placeholder
Placeholder

A placeholder is a general term, sign or symbol, which is used in place of a specific unknown or irrelevant term or value.Placeholder may also refer to:...
s marked by "%" escape character
Escape character

In computing and telecommunication, an escape character is a single character which in a sequence of characters signifies that what is to follow takes an alternative interpretation....
s, to specify both the relative location and the type of output that the function should produce.

1950s: FORTRAN, COBOL

FORTRANs variadic
Variadic function

In computer programming, a variadic function is a function of variable arity; that is, one which can take different numbers of arguments. Support for variadic functions differs widely among programming languages....
  PRINT statement took a reference to a non-executable FORMAT statement . PRINT, 601, 123456, 1000.0, 3.14, 250 601 FORMAT (7HRED NUM,I7,3HEXP, E7.1, 4HREAL ,F3.2, 3HVAL, I3)

will print the following line (including the CF LF characters):

RED NUM 123456 EXP 1.0E 03 REAL 3.14 VAL 250

1960s: BCPL, ALGOL 68, Multics PL/I

C's variadic
Variadic function

In computer programming, a variadic function is a function of variable arity; that is, one which can take different numbers of arguments. Support for variadic functions differs widely among programming languages....
 printf has its origins in BCPL
BCPL

BCPL is a computer programming language designed by Martin Richards of the University of Cambridge in 1966....
's writef function.

ALGOL 68
ALGOL 68

ALGOL 68 is an imperative programming computer programming programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously defined syntax and semantics....
 Draft and Final report had the functions inf and outf, subsequently these were revised out of the original language and replaced with the now more familiar readf/getf and printf/putf. printf(($"Color "g", number1 "6d,", number2 "4zd,", hex "16r2d,", float "-d.2d,", unsigned value"-3d"."l$, "red", 123456, 89, BIN 255, 3.14, 250));

Multics
Multics

Multics was an extremely influential early time-sharing operating system. The project was started in 1964. The last known running Multics installation was shut down on October 30, 2000....
 has a standard function called ioa_ with a wide variety of control codes. It was based on a machine-language facility from Multics's BOS (Bootstrap Operating System). call ioa_ ("Hello, ^a", "World!");

1970s: C, Lisp

printf("Color %s, number1 %d, number2 %05d, hex %x, float %5.2f, unsigned value %u.\n", "red", 123456, 89, 255, 3.14159, 250); will print the following line (including new-line character, \n): Color red, number1 123456, number2 00089, hex ff, float 3.14, unsigned value 250.

The printf function returns the number of characters printed, or a negative value if an output error occurs.

Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
 has the format function. (format t "Hello, ~a" "World!")

prints "Hello, World!" on the standard output stream. If the first argument is nil, format returns the string to its caller. The first argument can also be any output stream. format was introduced into ZetaLisp
ZetaLisp

ZetaLisp was the name Symbolics gave to their dialect of Lisp programming language on their Lisp Machine models, to distinguish it from the MIT version, which was called Lisp Machine Lisp....
 at M.I.T. in 1978, based on the Multics
Multics

Multics was an extremely influential early time-sharing operating system. The project was started in 1964. The last known running Multics installation was shut down on October 30, 2000....
 ioa_, and was later adopted into the Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
 standard.

1980s: perl

Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
 also has a printf function. Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
 has a format
Format (Common Lisp)

Format is a function in Common Lisp that can produce formatted text and is normally used in a manner analogous to printf in C and other curly bracket programming languages....
 function which acts according to the same principles as printf, but uses different characters for output conversion. The GLib
GLib

In computing, GLib refers to a cross-platform Library . It started off as part of the GTK+ project, however, before releasing version 2 of GTK+, the project's developers decided to separate non-GUI-specific code from the GTK+ platform, thus creating GLib as a separate product....
 library contains g_print, an implementation of printf.

Some Unix
Unix

Unix is a computer operating system originally developed in 1969 by a group of American Telephone & Telegraph employees at Bell Labs, including Ken Thompson , Dennis Ritchie, Douglas McIlroy, and Joe Ossanna....
 systems have a printf program for use in shell script
Shell script

A shell script is a Scripting language written for the Shell , or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language....
s. This can be used instead of echo
Echo (computing)

In computing, echo is a command in DOS, OS/2, Microsoft Windows, Singularity , Unix and Unix-like operating systems that places a String on the computer terminal....
 in situations where the latter is not portable. For example: echo -n -e "$FOO\t$BAR" may be rewritten portably as: printf "%s\t%s" "$FOO" "$BAR"

1990s: PHP, Python & Javascript

1991: Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
's % operator hearkens to printf's syntax when interpolating the contents of a tuple. This operator can, for example, be used with the print function: print("%s\t%s" % (foo,bar))

1995: PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 also has the printf function, with the same specifications and usage as that in C/C++. MATLAB
MATLAB

MATLAB is a Numerical analysis environment and programming language. Maintained by The MathWorks, MATLAB allows easy matrix manipulation, plotting of function and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages....
 does not have printf, but does have its two extensions sprintf and fprintf which use the same formatting strings.

1995: JavaScript
JavaScript

JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
 does not have a printf function, despite it being a curly bracket programming language
Curly bracket programming language

Curly brace or bracket programming languages are those which use balanced brackets to make block s in their syntax or formal grammar, mainly due to being C -influenced....
.

2000s: Java

2004: Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
 supported printf from version 1.5 onwards as a member of the PrintStream class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
, giving it the functionality of both the printf and fprintf functions. At the same time sprintf-like functionality was added to the String class by adding the format(String, Object... args) method. // Write "Hello, World!" to standard output (like printf) System.out.printf("%s, %s", "Hello", "World!"); // create a String object with the value "Hello, World!" (like sprintf) String myString = String.format("%s, %s", "Hello", "World!"); Unlike most other implementations, Java's implementation of printf throws an exception
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
 on encountering a malformed format string.

Derivative functions

The C Standard
C standard

C standard may refer to:* ANSI C or C99, specifications of the C programming language* C standard library* C tuning , a type of tuning for guitars...
 specifies a number of derivative functions to further leverage the printf functionality:

fprintf

int fprintf(FILE *stream, const char *format, ...)

fprintf enables printf output to be written to any file. Programmers frequently use it to print errors, by writing to the standard error
Standard streams

In Unix and Unix-like operating systems, as well as certain programming language interfaces, the standard streams are preconnected input and output channels between a computer program and its environment when it begins execution....
 device, but it can operate with any file opened with the fopen
Fopen

The C provides many standard library subroutine for computer file input/output. These functions make up the bulk of the C standard library header file ....
function.The same functionality is applicable in PRO * C also.

sprintf

int sprintf (char *str, const char *format, ...)

sprintf prints to a string (char array) instead of to standard output
Standard streams

In Unix and Unix-like operating systems, as well as certain programming language interfaces, the standard streams are preconnected input and output channels between a computer program and its environment when it begins execution....
. Users of sprintf must ensure, via calculation or via a guard page, that the resulting string will not be larger than the memory allocated for str. Failure to ensure this can allow a buffer overflow
Buffer overflow

In computer security and computer programming, a buffer overflow, or buffer overrun, is an Anomaly in software condition where a process attempts to store data beyond the boundaries of a fixed-length buffer ....
 to occur.

In higher-level languages such as PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 the sprintf function does not have the str argument. Instead, it returns the formatted output string. The prototype in PHP is like this:

string sprintf (const string format, ...)

Buffer safety and sprintf

In ISO C99, snprintf was introduced as an alternative to sprintf that can help avoid the risk of a buffer overflow:

int snprintf(char *str, size_t size, const char * restrict format, ...)

snprintf is guaranteed not to write more than size bytes into str, so use of it can help avoid the risk of a buffer overflow, as in the following code fragment:
  1. define BUFFER_SIZE 50
char buf[BUFFER_SIZE]; int n;

...

n = snprintf(buf, BUFFER_SIZE, "Your name is %s.\n", username); if (n > BUFFER_SIZE) /* Handle error */ If username in the above example exceeds 34 characters in length, the function will limit the string that gets saved in buf by cutting off final characters (truncating
Truncation (disambiguation)

The word truncation has several meanings.* In numerical analysis, truncation is the term used for reducing the number of digits right of the decimal point, by discarding the least significant ones....
). This may seem undesirable, but it is usually preferable to having a security vulnerability, which buffer overflows often cause. Additionally, the return code of snprintf indicates how many characters the function would have written to the string had enough space existed. Systems can use this information to allocate a new (larger) buffer if they require the whole string.

Another safe sprintf alternative is asprintf which is a GNU extension:

int asprintf(char **ret, const char *format, ...)

asprintf automatically allocates enough memory to hold the final string. It sets *ret to a pointer to the resulting string, or to an undefined value if an error occurred (GLibc is notable in being the only implementation that doesn't always set *ret to NULL
Null

Null is an English word meaning 'nothing' or without value or consequence. It is derived from the Latin word nullus meaning 'none'.Null may refer to:...
 on error). The programmer using asprintf has the responsibility of freeing the allocated memory after use. Though not part of any standard, asprintf comes in the C libraries of several operating systems (including OpenBSD
OpenBSD

OpenBSD is a Unix-like computer operating system descended from Berkeley Software Distribution , a Unix derivative developed at the University of California, Berkeley....
, FreeBSD
FreeBSD

FreeBSD is a Unix-like free software operating system descended from AT&T Unix via the Berkeley Software Distribution branch through the 386BSD and Berkeley Software Distribution#4.4BSD and descendants operating systems....
, and NetBSD
NetBSD

NetBSD is a freely redistributable, open source version of the Unix-derivative Berkeley Software Distribution computer operating system. It was the second open source BSD descendant to be formally released, after 386BSD, and continues to be actively developed....
) and on other platforms in the libiberty
Libiberty

GNU libiberty is a library with a collection of subroutines used by various GNU computer program.It was originally intended to be a sort of standard cross-platform library, thus enabling it to be linked by just saying "-liberty"....
 library.

GLib
GLib

In computing, GLib refers to a cross-platform Library . It started off as part of the GTK+ project, however, before releasing version 2 of GTK+, the project's developers decided to separate non-GUI-specific code from the GTK+ platform, thus creating GLib as a separate product....
 provides yet another safe alternative: g_strdup_printf, which allocates enough memory, but, unlike asprintf, returns the resulting string as its return value rather than via the first argument.

C++ alternatives to sprintf for numeric conversion

The standard method for string formatting and the conversion of other types to strings in C++ is iostream
Iostream

iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/Output Stream....
. Unlike printf, the iostream standard library is type-safe and extensible.

A common programming task is convert a numeric type into a string (char buffer). The sprintf family, while useful, in many applications seems like overkill for such a simple task.

A number of alternative means in C/C++ have been developed:
  • itoa
    Itoa

    The itoa function is a widespread non-standard extension to the standard C . It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header while in non-conforming mode, because it is a logical counterpart to the standard library function


vprintf, vfprintf, vsprintf, vsnprintf, and vasprintf

/* va_list versions of above */ int vprintf(const char *format, va_list ap); int vfprintf(FILE *stream, const char *format, va_list ap); int vsprintf(char *str, const char *format, va_list ap); int vsnprintf(char *str, size_t size, const char *format, va_list ap); int vasprintf(char **ret, const char *format, va_list ap);

These are analogous to the above functions without the vs, except that they use variable argument
Variadic function

In computer programming, a variadic function is a function of variable arity; that is, one which can take different numbers of arguments. Support for variadic functions differs widely among programming languages....
 lists. These functions offer the ability for programmers to essentially create their own printf variants. For instance, a programmer could write a function

void fatal_error(const char *format, ...)

which would use the va_start macro to obtain a va_list variable from the extra parameters, print a message on the standard error device using vfprintf, clean up after the va_list variable with the va_end macro, and finally perform the necessary tasks to cleanly shut down the program.

Another common application of these functions is to write a custom printf that prints to a different target than a file. For instance, a graphical library might provide a printf-like function with X and Y coordinates:

int graphical_printf(int x, int y, const char *format, ...)

This would work by temporarily saving the string to a private buffer using vsnprintf or vasprintf.

printf format placeholders

Formatting takes place via placeholders within the format string. For example, if a program wanted to print out a person's age, it could present the output by prefixing it with "Your age is ". To denote that we want the integer for the age to be shown immediately after that message, we may use the format string: "Your age is %d."

The syntax for a format placeholder is "%[parameter][flags][width][.precision][length]type".

  • Parameter can be omitted or can be:
Character Description
n$ n is the number of the parameter to display using this format specifier, allowing the parameters provided to be output multiple times, using varying format specifiers or in different orders. This is a POSIX
POSIX

POSIX or "Portable Operating System Interface" is the collective name of a family of related standardizations specified by the Institute of Electrical and Electronics Engineers to define the application programming interface , along with shell and utilities interfaces for software compatible with variants of the Unix operating system, altho...
 extension and not in C99
C99

C99 is a modern dialect of the C programming language....
. Example: printf("%2$d %1$#x %1$d",16,17) produces "17 0x10 16"


  • Flags can be zero or more (in any order) of:
Character Description
a number Causes printf to left-pad the output with spaces until the required length of output is attained. If combined with '0' (see below), it will cause the sign to become a space when positive, but the remaining characters will be zero-padded
+ Causes printf to always denote the sign '+' or '-' of a number (the default is to omit the sign for positive numbers). Only applicable to numeric types.
- Causes printf to left-align the output of this placeholder (the default is to right-align the output).
# Alternate form. For 'g' and 'G', trailing zeros are not removed. For 'f', 'F', 'e', 'E', 'g', 'G', the output always contains a decimal point. For 'o', 'x', and 'X', a 0, 0x, and 0X, respectively, is prepended to non-zero numbers.
0 Causes printf to use 0 instead of spaces to left-fill a fixed-length field. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".


  • Width can be omitted or be any of:
Character Description
a number Causes printf to pad the output of this placeholder with spaces until it is at least number characters wide. As mentioned above, if number has a leading '0', that is interpreted as a flag, and the padding is done with '0' characters instead of spaces.
* Causes printf to pad the output until it is n characters wide, where n is an integer value stored in the a function argument just preceding that represented by the modified type. For example printf("%*d", 5, 10) will result in "10" being printed with a width of 5.


  • Precision can be omitted or be any of:
Character Description
a number For non-integral numeric types, causes the decimal portion of the output to be expressed in at least number digits. For the string type, causes the output to be truncated at number characters. If the precision is zero, nothing is printed for the corresponding argument.
* Same as the above, but uses an integer value in the intaken argument to determine the number of decimal places or maximum string length. For example, printf("%.*s", 3, "abcdef") will result in "abc" being printed.


  • Length can be omitted or be any of:
Character Description
hh For integer types, causes printf to expect an int sized integer argument which was promoted from a char.
h For integer types, causes printf to expect a int sized integer argument which was promoted from a short.
l (ell) For integer types, causes printf to expect a long sized integer argument.
ll (ell ell) For integer types, causes printf to expect a long long sized integer argument.
L For floating point types, causes printf to expect a long double argument.
z For integer types, causes printf to expect a size_t sized integer argument.
j For integer types, causes printf to expect a intmax_t sized integer argument.
t For integer types, causes printf to expect a ptrdiff_t sized integer argument.


Additionally, several platform specific length options came to exist prior to widespread use of the ISO C99 extensions:
Characters Description
I For signed integer types, causes printf to expect ptrdiff_t sized integer argument; for unsigned integer types, causes printf to expect size_t sized integer argument. Commonly found in Win32/Win64 platforms.
I32 For integer types, causes printf to expect a 32-bit (double word) integer argument. Commonly found in Win32/Win64 platforms.
I64 For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in Win32/Win64 platforms.
q For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in BSD platforms.


ISO C99 includes the inttypes.h
Inttypes.h

The inttypes.h file is a C header file that is part of the C standard library and API. It was added with the 1999 version of the ISO C standard ....
header file that includes a number of macros for use in platform-independent printf coding. Example macros include:
Characters Description
"PRId32" Typically equivalent to I32d (Win32/Win64) or d
"PRId64" Typically equivalent to I64d (Win32/Win64), lld (32-bit platforms) or ld (64-bit platforms)
"PRIi32" Typically equivalent to I32i (Win32/Win64) or i
"PRIi64" Typically equivalent to I64i (Win32/Win64), lli (32-bit platforms) or li (64-bit platforms)
"PRIu32" Typically equivalent to I32u (Win32/Win64) or u
"PRIu64" Typically equivalent to I64u (Win32/Win64), llu (32-bit platforms) or lu (64-bit platforms)


  • Type can be any of:
Character Description
d, i Print an int as a signed decimal
Decimal

The decimal numeral system has 10 as its Base . It is the most widely used numeral system....
 number. '%d' and '%i' are synonymous for output, but are different when used with scanf
Scanf

scanf is a Function that reads data with specified format from a given string stream source, originated from C programming language, and is present in many other programming languages....
for input.
u Print decimal unsigned int.
f, F Print a double in normal (fixed-point) notation. 'f' and 'F' only differs in how the strings for an infinite number or NaN are printed ('inf', 'infinity' and 'nan' for 'f', 'INF', 'INFINITY' and 'NAN' for 'F').
e, E Print a double value in standard form ([-]d.ddd e[+/-]ddd).An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00.
g, G Print a double in either normal or exponential notation, whichever is more appropriate for its magnitude. 'g' uses lower-case letters, 'G' uses upper-case letters. This type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included. Also, the decimal point is not included on whole numbers.
x, X Print an unsigned int as a hexadecimal
Hexadecimal

In mathematics and computer science, hexadecimal is a numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 09 to represent values zero to nine, and A, B, C, D, E, F to represent values ten to fifteen....
 number. 'x' uses lower-case letters and 'X' uses upper-case.
o Print an unsigned int in octal.
s Print a character string.
c Print a char (character).
p Print a void * (pointer to void) in an implementation-defined format.
n Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
% Print a literal '%' character (this type doesn't accept any flags, width, precision or length).


If the syntax
Syntax

In linguistics, syntax is the study of the principles and rules for constructing Sentence s in natural languages. In addition to referring to the discipline, the term syntax is also used to refer directly to the rules and principles that govern the sentence structure of any individual language, as in "the Irish syntax"....
 of a conversion specification is invalid, behavior remains undefined, and in fact can cause program termination. If there are too few 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 also undefined. Excess arguments are ignored. In a number of cases, the undefined behavior has led to "Format string attack
Format string attack

Format string attacks are a class of Exploit discovered around 1999. Previously thought harmless, Format string attacks can be used to Crash a program or to execute harmful code....
" security vulnerabilities.

Note that some compilers, like the GNU Compiler Collection
GNU Compiler Collection

The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain....
, will statically check the format strings of printf-like functions and warn about problems (specially by using the flags -Wall or -Wformat). The GNU Compiler Collection
GNU Compiler Collection

The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain....
 will also warn about user-defined printf-style functions if the non-standard "format" __attribute__ is applied to the function.

Risks of using field width versus explicit delimiters in tabular output

Using only field widths to provide for tabulation, as with a format like "%8d%8d%8d" for three integers in three 8-character columns, will not guarantee that field separation will be retained if large numbers occur in the data. Loss of field separation can easily lead to corrupt output. In systems which encourage the use of programs as building blocks in scripts, such corrupt data can often be forwarded into and corrupt further processing, regardless of whether the original programmer expected the output would only be read by human eyes. Such problems can be eliminated by including explicit delimiters, even spaces, in all tabular output formats. Simply changing the dangerous example from before to " %7d %7d %7d" addresses this, formatting identically until numbers become larger, but then explicitly preventing them from becoming merged on output due to the explicitly-included spaces. Similar strategies apply to string data.

Custom printf format placeholders

There are a few implementations of printf-like functions that allow extensions to the escape-character
Escape character

In computing and telecommunication, an escape character is a single character which in a sequence of characters signifies that what is to follow takes an alternative interpretation....
-based mini-language
Domain-specific programming language

In software development, a domain-specific language is a programming language or specification language dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique....
, thus allowing the programmer to have a specific formatting function for non-builtin types. One of the most well-known is glibc's . However, it is rarely used due to the fact that it conflicts with static format string checking. Another is , which allows adding multi-character format names, and can work with static format checkers.

Some applications (like the Apache HTTP Server
Apache HTTP Server

The Apache HTTP Server, commonly referred to simply as Apache , is a web server notable for playing a key role in the initial growth of the World Wide Web....
) include their own printf-like function, and embed extensions into it. However these all tend to have the same problems that register_printf_function has.

Most non-C languages that have a printf-like function work around the lack of this feature by just using the "%s" format and converting the object to a string representation. C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 offers a notable exception, in that it has a printf function inherited from its C history, but also has a completely different mechanism that is preferred.

Programming languages with printf

  • AMPL
  • awk
  • Bourne shell
    Bourne shell

    The Bourne shell, or sh, was the default Unix shell of Version 7 Unix, and replaced the Thompson shell, whose executable file had the same name, sh....
     (sh) and derivatives such as Korn shell
    Korn shell

    The Korn shell is a Unix shell which was developed by David Korn in the early 1980s. It is backwards-compatible with the Bourne shell and includes many features of the C shell as well, such as a command history, which was inspired by the requests of Bell Labs users....
     (ksh), Bourne again shell (bash), or Z shell
    Z shell

    The Z shell is a Unix shell that can be used as an interactive login shell and as a powerful command line interpreter for shell scripting. Zsh can be thought of as an extended Bourne shell with a large number of improvements, including some of the most useful features of bash, Korn shell, and tcsh....
     (zsh)
  • C programming language
    C (programming language)

    C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
    , and subsequently C++
    C++

    C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
     and Obj-C (C++ also provides overloaded shift operators and manipulators as an alternative for formatted output - see iostream
    Iostream

    iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/Output Stream....
     and iomanip)
  • F Sharp (programming language)
  • GNU Octave
    GNU Octave

    Octave is a computer program for performing numerical analysis which is mostly compatible with MATLAB. It is part of the GNU Project. It is free software under the terms of the GNU General Public License....
  • Haskell
  • Java programming language
    Java (programming language)

    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
     (since version 1.5)
  • Maple
    Maple

    Acer is a genus of trees or shrubs commonly known as Maple. Maples are variously classified in a family of their own, the Aceraceae, or included in the family Sapindaceae....
  • Mathematica
    Mathematica

    Mathematica is a computational software program used widely in scientific, engineering, and mathematical fields and other areas of technical computing....
  • MATLAB
    MATLAB

    MATLAB is a Numerical analysis environment and programming language. Maintained by The MathWorks, MATLAB allows easy matrix manipulation, plotting of function and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages....
  • Objective Caml
    Objective Caml

    Objective Caml, or OCaml is the main implementation of the Caml programming language, created by Xavier Leroy, J?r?me Vouillon, Damien Doligez, Didier R?my and others in 1996....
  • PHP
    PHP

    PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
     programming language, web-based inflected form of C
  • Python programming language
    Python (programming language)

    Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
     (using the % operator)
  • Perl
    Perl

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
  • Ruby programming language
    Ruby (programming language)

    Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....


See also

  • scanf
    Scanf

    scanf is a Function that reads data with specified format from a given string stream source, originated from C programming language, and is present in many other programming languages....
  • C standard library
    C standard library

    The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and character string handling, in the C ....
  • Format string attack
    Format string attack

    Format string attacks are a class of Exploit discovered around 1999. Previously thought harmless, Format string attacks can be used to Crash a program or to execute harmful code....
  • iostream
    Iostream

    iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/Output Stream....


External links

  • *The in Java 1.5
  • *