In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.
The term variadic is a neologism, dating back to 1936–1937.[1] The term was not widely used until the 1970s.
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 be thought of as applicable to any number of operands (even though formally in these cases the associative property is applied).
Another operation that has been implemented as a variadic function in many languages is output formatting. The C function and the Common Lisp function 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, if used incautiously, 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. As a consequence of this, the CERT Coordination Center considers variadic functions in C to be a high-severity security risk.[2]
In functional programming languages, variadics can be considered complementary to the apply function, which takes a function and a list/sequence/array as arguments, and calls the function with the arguments supplied in that list, thus passing a variable number of arguments to the function. In the functional language Haskell, variadic functions can be implemented by returning a value of a type class ; if instances of are a final return value and a function, this allows for any number of additional arguments .
A related subject in term rewriting research is called hedges, or hedge variables.[3] Unlike variadics, which are functions with arguments, hedges are sequences of arguments themselves. They also can have constraints ('take no more than 4 arguments', for example) to the point where they are not variable-length (such as 'take exactly 4 arguments') - thus calling them variadics can be misleading. However they are referring to the same phenomenon, and sometimes the phrasing is mixed, resulting in names such as variadic variable (synonymous to hedge). Note the double meaning of the word variable and the difference between arguments and variables in functional programming and term rewriting. For example, a term (function) can have three variables, one of them a hedge, thus allowing the term to take three or more arguments (or two or more if the hedge is allowed to be empty).
To portably implement variadic functions in the C language, the standard header file is used. The older header has been deprecated in favor of . In C++, the header file is used.[4]
double average(int count, ...)
int main(int argc, char const *argv[])
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 expects that the types will be, and that the number of arguments is passed in the first argument (this is a frequent usage but by no means enforced by the language or compiler). In some other cases, for example printf, the number and types of arguments are figured out from a format string. In both cases, this depends on the programmer to supply the correct information. (Alternatively, a sentinel value like may be used to indicate the number.) 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.
declares a type,, and defines four macros:,,, and . Each invocation of and must be matched by a corresponding invocation of . When working with variable arguments, a function normally declares a variable of type (in the example) that will be manipulated by the macros.
C# describes variadic functions using the keyword. A type must be provided for the arguments, although can be used as a catch-all. At the calling site, you can either list the arguments one by one, or hand over a pre-existing array having the required element type. Using the variadic form is Syntactic sugar for the latter.
class Program
The basic variadic facility in C++ is largely identical to that in C. The only difference is in the syntax, where the comma before the ellipsis can be omitted. C++ allows variadic functions without named parameters but provides no way to access those arguments since va_start
requires the name of the last fixed argument of the function.
void simple_printf(const char* fmt...) // C-style "const char* fmt, ..." is also valid
int main
Variadic templates (parameter pack) can also be used in C++ with language built-in fold expressions.
template
int main
The CERT Coding Standards for C++ strongly prefers the use of variadic templates (parameter pack) in C++ over the C-style variadic function due to a lower risk of misuse.[6]
Variadic functions in Go can be called with any number of trailing arguments.[7] is a common variadic function; it uses an empty interface as a catch-all type.
import "fmt"
// This variadic function takes an arbitrary number of ints as arguments.func sum(nums ...int)
func main
Output:
The sum of [1 2] is 3 The sum of [1 2 3] is 6 The sum of [1 2 3 4] is 10
As with C#, the type in Java is available as a catch-all.
JavaScript does not care about types of variadic arguments.
console.log(sum(1, 2, 3)); // 6console.log(sum(3, 2)); // 5console.log(sum); // 0
It's also possible to create a variadic function using the arguments object, although it is only usable with functions created with the keyword.
console.log(sum(1, 2, 3)); // 6console.log(sum(3, 2)); // 5console.log(sum); // 0
Lua functions may pass varargs to other functions the same way as other values using the keyword. tables can be passed into variadic functions by using, in Lua version 5.2 or higher[8], or Lua 5.1 or lower[9] . Varargs can be used as a table by constructing a table with the vararg as a value.
values=sum(5,table.unpack(values)) --returns 15. table.unpack should go after any other arguments, otherwise not all values will be passed into the function.
function add5(...) return ...+5 --this is incorrect usage of varargs, and will only return the first value providedend
entries=function process_entries local processed= for i,v in pairs(entries) do processed[i]=v --placeholder processing code end return table.unpack(processed) --returns all entries in a way that can be used as a varargend
print(process_entries) --the print function takes all varargs and writes them to stdout separated by newlines
Pascal is standardized by ISO standards 7185 (“Standard Pascal”) and 10206 (“Extended Pascal”).Neither standardized form of Pascal supports variadic routines, except for certain built-in routines (/ and /, and additionally in /).
Nonetheless, dialects of Pascal implement mechanisms resembling variadic routines.Delphi defines an data type that may be associated with the last formal parameter.Within the routine definition the is an, an array of variant records.[10] The member of the aforementioned data type allows inspection of the argument’s data type and subsequent appropriate handling.The Free Pascal Compiler supports Delphi’s variadic routines, too.[11]
This implementation, however, technically requires a single argument, that is an .Pascal imposes the restriction that arrays need to be homogenous.This requirement is circumvented by utilizing a variant record.The GNU Pascal defines a real variadic formal parameter specification using an ellipsis, but as of 2022 no portable mechanism to use such has been defined.[12]
Both GNU Pascal and FreePascal allow externally declared functions to use a variadic formal parameter specification using an ellipsis .
PHP does not care about types of variadic arguments unless the argument is typed.
echo sum(1, 2, 3); // 6
And typed variadic arguments:
echo sum(1, 'a', 3); // TypeError: Argument 2 passed to sum must be of the type int (since PHP 7.3)
Python does not care about types of variadic arguments.
foo(1, 2) # foo(1, 2, 3) # (3,)foo(1, 2, 3, "hello") # (3, "hello")
Keyword arguments can be stored in a dictionary, e.g. .
In Raku, the type of parameters that create variadic functions are known as slurpy array parameters and they're classified into three groups:
These parameters are declared with a single asterisk (*
) and they flatten arguments by dissolving one or more layers of elements that can be iterated over (i.e, Iterables).
foo(1, 2) # []foo(1, 2, 3) # [3]foo(1, 2, 3, "hello") # [3 "hello"]foo(1, 2, 3, [4, 5], [6]); # [3, 4, 5, 6]
These parameters are declared with two asterisks (**
) and they do not flatten any iterable arguments within the list, but keep the arguments more or less as-is:
bar(1, 2); # []bar(1, 2, 3); # [3]bar(1, 2, 3, "hello"); # [3 "hello"]bar(1, 2, 3, [4, 5], [6]); # [3, [4, 5], [6]]
These parameters are declared with a plus (+
) sign and they apply the "single argument rule", which decides how to handle the slurpy argument based upon context. Simply put, if only a single argument is passed and that argument is iterable, that argument is used to fill the slurpy parameter array. In any other case, +@
works like **@
(i.e., unflattened slurpy).
zaz(1, 2); # []zaz(1, 2, 3); # [3]zaz(1, 2, 3, "hello"); # [3 "hello"]zaz(1, 2, [4, 5]); # [4, 5], single argument fills up arrayzaz(1, 2, 3, [4, 5]); # [3, [4, 5]], behaving as **@zaz(1, 2, 3, [4, 5], [6]); # [3, [4, 5], [6]], behaving as **@
Ruby does not care about types of variadic arguments.
foo(1)
foo(1, 2)
Rust does not support variadic arguments in functions. Instead, it uses macros.[13]
fn main
Rust is able to interact with C's variadic system via a feature switch. As with other C interfaces, the system is considered to Rust.[14]
Swift cares about the type of variadic arguments, but the catch-all type is available.
greet(timeOfTheDay: "morning", names: "Joseph", "Clara", "William", "Maria")
// Output:// Looks like we have 4 people// Hello Joseph, good morning// Hello Clara, good morning// Hello William, good morning// Hello Maria, good morning
A Tcl procedure or lambda is variadic when its last argument is : this will contain a list (possibly empty) of all the remaining arguments. This pattern is common in many other procedure-like methods.[15] [16]
greet "morning" "Joseph" "Clara" "William" "Maria"