Variadic function

This is an old revision of this page, as edited by 84.196.134.122 (talk) at 03:03, 12 July 2006 (Disambiguating nomenclature by using"adicity" rather than "arity"). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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.

There are many mathematical and logical operations which come across naturally as variadic functions. For instance, the summing of numbers or the concatenation of strings or other sequences are operations that can logically apply to any number of operands.

Another operation which has been implemented as a variadic function in many languages is output formatting. The C function printf and the Common Lisp function format are two such examples. Both take one argument which specifies the formatting of the output, and any number of arguments which provide the values to be formatted.

Variadic functions can expose type-safety problems in some languages. For instance, C's printf, if used uncautiously, can give rise to a class of security holes known as format string attacks. The attack is possible because the language support for variadic functions is not type-safe; it permits the function to attempt to pop more arguments off the stack than were placed there -- corrupting the stack and leading to unexpected behavior.

To portably implement variadic functions in the C programming language, the standard <stdarg.h> header file should be used. The older <varargs.h> header has been deprecated in favor of <stdarg.h>.

In PHP, variable-length argument lists are natively supported (without security risk) since version 4; dedicated functions (func_num_args, func_get_arg, func_get_args) allow the programmer to determine the number and values of unspecified arguments.

Suggestion on terminology

In a wider context, it is recommended using the term adicity for the number of arguments of a function and reserve the term arity for the number of values that a function argument can take. In this way, terms such as binary functions and ternary functions would designate functions as found in binary algebra and ternary algebra (or binary logic and ternary logic) respectively. By the same token, the adjectives monadic and dyadic can then refer in an orthogonal way to the number of arguments of such functions. For instance, the commonly used logical "not" denotes a monadic binary function, whereas "and" denotes a dyadic binary function (with appropriate ternary variants).

In this way, a more disciplined use of already existing terms avoids ambiguity and serves orthogonality.

(Suggestion added by Raymond.Boute@pandora.be)

See also

Variadic macro (C Programming Language)