Variadic function

This is an old revision of this page, as edited by MFH (talk | contribs) at 19:37, 12 May 2005 (subsection for optional args). 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.

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.

Optional arguments with default values

Besides the concept of a completely arbitrary number of arguments as discussed above, the declaration of default values for some of the specified arguments is another concept allowing to call a function with variable number of arguments. Several typed languages implement this, and can in some cases associate the arguments to the corresponding variables in view of their type, even if they are given at call-time in an order differing from the declaration. In languages which are not (strongly) typed (such as PHP), such optional arguments with default values cannot precede mandatory arguments without default value. (An exception are some system functions of PHP, like the implode function, that can associate arguments given in any order to the right variables, in view of their type.)

See Also

Variadic macro (C Programming Language)