Variadic function
Encyclopedia
In computer programming
, a variadic function is a function of indefinite arity
, i.e., one which accepts a variable number of argument
s. Support for variadic functions differs widely among programming language
s.
There are many mathematical and logical operations that 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 that 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 that specifies the formatting of the output, and any number of arguments that provide the values to be formatted.
Variadic functions can expose type-safety problems in some languages. For instance, C's printf, if used incautiously, can give rise to a class of security holes known as format string attack
s. 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.
Variadic functionality can be considered complementary to the apply
function, which takes a function and a list/sequence/array as arguments and then calls the function once, with the arguments being the elements of the list.
Note that this uses the standard lisp add function which itself is a variadic function.
Common Lisp also provides the &body specifier for situations where multiple statements of code are being passed in as parameters (generally when implementing syntactic macros). While such situations can equivalently be handled by &rest, &body is preferred because it conveys the author's intent more specifically. For example, here is a re-implementation of prog1, a macro that returns the result of the first of a block of statements:
Like Python, Common Lisp provides a facility for optional parameters and named parameters (also called dictionary parameters). For instance, consider this function whose second parameter takes a default value if unspecified:
When invoked with a single parameter N, the result will be N + 1. When invoked with two parameters X and Y, the result will be X + Y.
Parameters may also be given out-of-order. Consider, for instance, a function that constructs a tuple representing a data item. Such a function could be implemented like this:
header file should be used. The older varargs.h header has been deprecated
in favor of stdarg.h. In C++, the header file cstdarg should be used.
To create a variadic function, an ellipsis (
This will compute the average of an arbitrary number of arguments. Note that the function does not know the number of arguments or their types. The above function requires that the types be
, the number and types of arguments are figured out from a format string. In both cases, this depends on the programmer to actually supply the correct information. If fewer arguments are passed in than the function believes, or the types of arguments are incorrect, this could cause it to read into invalid areas of memory and can lead to vulnerabilities like the format string attack
.
Objective-C uses the same varargs functionality as C. Like C, it has no way of knowing the number or types of the arguments. When the arguments are all objects, the convention is that, if the number of arguments is undetermined, then the list must be "terminated" with
In the current standard of C++
, C++11, templates may also take variadic argument lists; this feature is called variadic templates
. This allows the creation of variadic template classes and variadic template functions. Variadic templates will finally allow the creation of true tuple
classes in C++.
Variadic templates similar to this exist in D
:
use a different approach—they just allow a variable number of arguments of the same (super)type to be passed to a variadic function. Inside the method they are simply collected in an array.
This feature, called "varargs", has been introduced to Java in J2SE 5.0. Parameters are passed as an array:
C# Example:
VB.Net example:
C++.NET Example:
's type system can be used to make functions that seem to be able to take an unlimited number of arguments, of different types.
, the arguments to a function may be accessed individually as local variables within the function. Additionally, the arguments may be accessed together as members of a local object called
provides a standard syntax for parsing all or part of JavaScript's
If there are any other variables in the argument list, those take precedence. So
defines a function that, given two or fewer arguments, will return an empty array; but given three or more arguments, will return an array containing all but the first and last.
5, functions don't have an explicit list of parameters (except optional prototypes that are used to imitate certain syntax, i.e., when reimplementing some built-in functions). All arguments are stored in an array called
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
, a variadic function is a function of indefinite arity
Arity
In logic, mathematics, and computer science, the arity of a function or operation is the number of arguments or operands that the function takes. The arity of a relation is the dimension of the domain in the corresponding Cartesian product...
, i.e., one which accepts a variable number of argument
Argument
In philosophy and logic, an argument is an attempt to persuade someone of something, or give evidence or reasons for accepting a particular conclusion.Argument may also refer to:-Mathematics and computer science:...
s. Support for variadic functions differs widely among programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
s.
There are many mathematical and logical operations that 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 that has been implemented as a variadic function in many languages is output formatting. The C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
function printf
Printf
Printf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for rendering an arbitrary number of varied data type parameter into a string...
and the Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...
function 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...
are two such examples. Both take one argument that specifies the formatting of the output, and any number of arguments that provide the values to be formatted.
Variadic functions can expose type-safety problems in some languages. For instance, C's printf, if used incautiously, can give rise to a class of security holes known as format string attack
Format string attack
Uncontrolled format string is a type of software vulnerability, discovered around 1999, that can be used in security exploits. Previously thought harmless, format string exploits can be used to crash a program or to execute harmful code...
s. The attack is possible because the language support for variadic functions is not type-safe
Type safety
In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behaviour caused by a discrepancy between differing data types...
; 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.
Variadic functionality can be considered complementary to the apply
Apply
In mathematics and computer science, Apply is a function that applies functions to arguments. It is central to programming languages derived from lambda calculus, such as LISP and Scheme, and also in functional languages...
function, which takes a function and a list/sequence/array as arguments and then calls the function once, with the arguments being the elements of the list.
Specific implementations
The following provides an overview of specific implementations in different programming languages and environments.Variadic functions in Common Lisp
Common Lisp uses the &rest argument specifier to implement variadic functions. At execution time, the &rest variable collects all following arguments into one list. For example:Note that this uses the standard lisp add function which itself is a variadic function.
Common Lisp also provides the &body specifier for situations where multiple statements of code are being passed in as parameters (generally when implementing syntactic macros). While such situations can equivalently be handled by &rest, &body is preferred because it conveys the author's intent more specifically. For example, here is a re-implementation of prog1, a macro that returns the result of the first of a block of statements:
Like Python, Common Lisp provides a facility for optional parameters and named parameters (also called dictionary parameters). For instance, consider this function whose second parameter takes a default value if unspecified:
When invoked with a single parameter N, the result will be N + 1. When invoked with two parameters X and Y, the result will be X + Y.
Parameters may also be given out-of-order. Consider, for instance, a function that constructs a tuple representing a data item. Such a function could be implemented like this:
Variadic functions in C, Objective-C, C++, and D
To portably implement variadic functions in the C programming language, the standard stdarg.hStdarg.h
stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. It provides facilities for stepping through a list of function arguments of unknown number and type...
header file should be used. The older varargs.h header has been deprecated
Deprecation
In the process of authoring computer software, its standards or documentation, deprecation is a status applied to software features to indicate that they should be avoided, typically because they have been superseded...
in favor of stdarg.h. In C++, the header file cstdarg should be used.
To create a variadic function, an ellipsis (
...
) must be placed at the end of a parameter list. Inside the body of the function, a variable of type va_list
must be defined. Then the macros va_start(va_list, last fixed param)
, va_arg(va_list, cast type)
, va_end(va_list)
can be used. For example:This will compute the average of an arbitrary number of arguments. Note that the function does not know the number of arguments or their types. The above function requires that the types be
double
, and the number of arguments is passed in the first argument. In some other cases, for example printfPrintf
Printf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for rendering an arbitrary number of varied data type parameter into a string...
, the number and types of arguments are figured out from a format string. In both cases, this depends on the programmer to actually supply the correct information. If fewer arguments are passed in than the function believes, or the types of arguments are incorrect, this could cause it to read into invalid areas of memory and can lead to vulnerabilities like the format string attack
Format string attack
Uncontrolled format string is a type of software vulnerability, discovered around 1999, that can be used in security exploits. Previously thought harmless, format string exploits can be used to crash a program or to execute harmful code...
.
Objective-C uses the same varargs functionality as C. Like C, it has no way of knowing the number or types of the arguments. When the arguments are all objects, the convention is that, if the number of arguments is undetermined, then the list must be "terminated" with
nil
. Functions that follow this convention include the constructors of data structures that take an undetermined number of elements, like [NSArray arrayWithObjects:...]
.In the current standard of C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, C++11, templates may also take variadic argument lists; this feature is called variadic templates
Variadic Templates
In computer programming, variadic templates are templates that take a variable number of arguments.Variadic templates are supported by the D programming language, and the newest version of C++, formalized in the C++11 standard.-C++11:...
. This allows the creation of variadic template classes and variadic template functions. Variadic templates will finally allow the creation of true tuple
Tuple
In mathematics and computer science, a tuple is an ordered list of elements. In set theory, an n-tuple is a sequence of n elements, where n is a positive integer. There is also one 0-tuple, an empty sequence. An n-tuple is defined inductively using the construction of an ordered pair...
classes in C++.
Variadic templates similar to this exist in D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...
:
Variadic functions in C#, C++.net, VB.net, and Java
Other languages, such as C#, VB.net, and JavaJava (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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
use a different approach—they just allow a variable number of arguments of the same (super)type to be passed to a variadic function. Inside the method they are simply collected in an array.
This feature, called "varargs", has been introduced to Java in J2SE 5.0. Parameters are passed as an array:
C# Example:
VB.Net example:
C++.NET Example:
Variadic functions in Haskell
HaskellHaskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
's type system can be used to make functions that seem to be able to take an unlimited number of arguments, of different types.
Variadic functions in JavaScript
In JavaScriptJavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
, the arguments to a function may be accessed individually as local variables within the function. Additionally, the arguments may be accessed together as members of a local object called
arguments
. The arguments
object is not a true array, but rather an array-like object that possesses a length
property.Variadic functions in CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript is a programming language that transcompiles to JavaScript. The language adds syntactic sugar inspired by Ruby, Python and Haskell to enhance JavaScript's brevity and readability, as well as adding more sophisticated features like array comprehension and pattern matching...
provides a standard syntax for parsing all or part of JavaScript's
arguments
object into an array. The splat operator ...
may be appended after a variable in the argument list to have that variable "soak up" any remaining arguments. For instance, the above JavaScript could be rewritten asIf there are any other variables in the argument list, those take precedence. So
defines a function that, given two or fewer arguments, will return an empty array; but given three or more arguments, will return an array containing all but the first and last.
Variadic functions in Perl
In PerlPerl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
5, functions don't have an explicit list of parameters (except optional prototypes that are used to imitate certain syntax, i.e., when reimplementing some built-in functions). All arguments are stored in an array called
@_, which can be accessed in the function. Therefore no special effort is needed to accept variable number of arguments.
Variadic functions in PHP
In PHPPHPPHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
, variable-length argument lists are natively supported (without security risks) 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.
Variadic functions in Python
PythonPython (programming language)Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
supports very flexible variadic functions. By marking variables with one asterisk (e.g. *var
) the given variable is defined to be a tuple of all the extra arguments. By marking variables with two asterisks (e.g. **var
) the given variable is a dictionary of all extra keyword argumentsParameter (computer science)In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...
; the keys are strings, which are the names that were used to identify the arguments. If they exist, these arguments must be the last one in the list.
Conversely you may also pass in a tuple or dictionary using the same asterisk-notation and have it automatically expand to fill.
Variadic functions in S-Lang
S-Lang supports two mechanisms for passing optional arguments to a
function. The two mechanisms are illustrated by the readascii
function that is distributed as part of the S-Lang library. The
function is used to read one or more data columns from an ascii (as
opposed to binary) file:
The optional keyword/value pairs that follow the semi-colon in the
argument list are called qualifiers in S-Lang parlance.
When a function is called, the "_NARGS
" variable contains the number
of arguments passed to the function. This value does not include the
number of qualifiers. Here is a simple example that performs the sum
of the arguments (assumed here to be numeric) passed to a function:
Here is a variant of the above that uses a qualifier to alternate
between the sum and difference of the successive arguments. This
example makes use of the built-in sum function to add the elements of
an array.
Variadic functions in Ruby
RubyRuby (programming language)Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
supports variadic functions natively. An asterisk before the last parameter in the function declaration declares that parameter to be an array into which all remaining input arguments are placed.
Variadic functions in Scheme
In Scheme, there is a dotted notation for representing improper lists (chains of pairs whose last cdr is not null). You can use this notation in argument lists to specify an argument to "dump" the rest of the arguments into.
If a function is defined with the "define
" syntax, then you put a dot before the varargs argument
If a function is defined with the "lambda
" syntax, then it is the same thing, except that if there are no arguments before the varargs argument (i.e. if you want to put all the arguments into one thing), then you remove the parentheses altogether; as if to say, let this be the entire argument list.
Variadic functions in Tcl
In Tcl a variadic argument can be defined as last argument and must be named args
. The content of args is a list.
Variadic functions are used very often to process key-value lists.
Variadic functions in Lua
Lua supports variadic functions, by use of a special named parameter "..."
See also
- ComputingComputingComputing is usually defined as the activity of using and improving computer hardware and software. It is the computer-specific part of information technology...
- Java syntaxJava syntaxThe syntax of the Java programming language is a set of rules which defines how a Java program is written and interpreted.The syntax is mostly derived from C and C++. Unlike C++, Java is almost exclusively an object-oriented language. There are no global functions or variables, all code belongs to...
- Variadic macroVariadic macroA variadic macro is a feature of the C preprocessor whereby a macro may be declared to accept a varying number of arguments.Variable-argument macros were introduced in the ISO/IEC 9899:1999 revision of the C programming language standard in 1999...
(C programming language)
- Variadic templatesVariadic TemplatesIn computer programming, variadic templates are templates that take a variable number of arguments.Variadic templates are supported by the D programming language, and the newest version of C++, formalized in the C++11 standard.-C++11:...
External links
- Variadic function. Rosetta CodeRosetta CodeRosetta Code is a wiki-based programming chrestomathy website with solutions to various programming problems in many different programming languages. It was created in 2007 by Mike Mol. Rosetta Code includes 450 programming tasks, and covers 351 programming languages...
task showing the implementation of variadic functions in over fifty programming languages.
- Variable Argument Functions — A tutorial on Variable Argument Functions for C++
- GNU libc manual