Variadic function
   HOME

TheInfoList



OR:

In
mathematics Mathematics is an area of knowledge that includes the topics of numbers, formulas and related structures, shapes and the spaces in which they are contained, and quantities and their changes. These topics are represented in modern mathematics ...
and in
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a variadic function is a function of indefinite
arity Arity () is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named ''rank'', but this word can have many other meanings in mathematics. ...
, i.e., one which accepts a variable number of
argument An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialecti ...
s. Support for variadic functions differs widely among
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s. The term ''variadic'' is a
neologism A neologism Ancient_Greek.html"_;"title="_from_Ancient_Greek">Greek_νέο-_''néo''(="new")_and_λόγος_/''lógos''_meaning_"speech,_utterance"is_a_relatively_recent_or_isolated_term,_word,_or_phrase_that_may_be_in_the_process_of_entering_com ...
, dating back to 1936–1937. The term was not widely used until the 1970s.


Overview

There are many mathematical and logical operations that come across naturally as variadic functions. For instance, the summing of numbers or the
concatenation In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenat ...
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 In mathematics, the associative property is a property of some binary operations, which means that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replaceme ...
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 Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
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 Stack may refer to: Places * Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group * Blue Stack Mountains, in Co. Donegal, Ireland People * Stack (surname) (including a list of people ...
than were placed there, corrupting the stack and leading to unexpected behavior. As a consequence of this, the
CERT Coordination Center The CERT Coordination Center (CERT/CC) is the coordination center of the computer emergency response team (CERT) for the Software Engineering Institute (SEI), a non-profit United States federally funded research and development center. The CERT/C ...
considers variadic functions in C to be a high-severity security risk. In functional languages variadics can be considered complementary to the
apply In mathematics and computer science, apply is a function that applies a function to arguments. It is central to programming languages derived from lambda calculus, such as LISP and Scheme, and also in functional languages. It has a role in the ...
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 In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T an ...
; 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 In mathematics, computer science, and logic, rewriting covers a wide range of methods of replacing subterms of a formula with other terms. Such methods may be achieved by rewriting systems (also known as rewrite systems, rewrite engines, or r ...
research is called hedges, or hedge variables. 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).


Examples


In C

To portably implement variadic functions in the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well a ...
, the standard header file is used. The older header has been
deprecated In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing ...
in favor of . In C++, the header file is used. #include #include 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 printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
, 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. # takes two arguments, a object and a reference to the function's last parameter (the one before the ellipsis; the macro uses this to get its bearings). In C23, the second argument will no longer be required and variadic functions will no longer need a named parameter before the ellipsis. It initialises the object for use by or . The compiler will normally issue a warning if the reference is incorrect (e.g. a reference to a different parameter than the last one, or a reference to a wholly different object), but will not prevent compilation from completing normally. # takes two arguments, a object (previously initialised) and a type descriptor. It expands to the next variable argument, and has the specified type. Successive invocations of allow processing each of the variable arguments in turn. Unspecified behavior occurs if the type is incorrect or there is no next variable argument. # takes one argument, a object. It serves to clean up. If one wanted to, for instance, scan the variable arguments more than once, the programmer would re-initialise your object by invoking and then again on it. # takes two arguments, both of them objects. It clones the second (which must have been initialised) into the first. Going back to the "scan the variable arguments more than once" example, this could be achieved by invoking on a first , then using to clone it into a second . After scanning the variable arguments a first time with and the first (disposing of it with ), the programmer could scan the variable arguments a second time with and the second . needs to also be called on the cloned before the containing function returns.


In C#

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 In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
for the latter. using System; class Program


In C++

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. #include #include 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. #include template void foo_print(Ts... args) 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.


In Go

Variadic functions in Go can be called with any number of trailing arguments. is a common variadic function; it uses an empty interface as a catch-all type. package main import "fmt" // This variadic function takes an arbitrary number of ints as arguments. func sum(nums ...int) func main() Output:
The sum of   2is 3 
The sum of   2 3is 6 
The sum of   2 3 4is 10


In Java

As with C#, the type in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
is available as a catch-all. public class Program


In JavaScript

JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
does not care about types of variadic arguments. function sum(...numbers) console.log(sum(1, 2, 3)); // 6 console.log(sum(3, 2)); // 5 console.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. function sum() console.log(sum(1, 2, 3)); // 6 console.log(sum(3, 2)); // 5 console.log(sum()); // 0


In

Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...

Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...
has four built-in procedures which are defined as variadic, which, because of this special condition, are intrinsic to the compiler. These are the , , , and procedures. However, there are alternate specifications allowing for ''default'' arguments to procedures or functions which make them work variadically, as well as '' polymorphism'' which allows a procedure or function to have different parameters. The and procedures all have the same format:
read n _ _[file_,variable_[,_variable_...">ile_,.html"_;"title="_[file_,">_[file_,variable_[,_variable_...).html" ;"title="ile_,variable_[,_variable_....html" ;"title="ile_,.html" ;"title=" [file ,"> [file ,variable [, variable ...">ile_,.html" ;"title=" [file ,"> [file ,variable [, variable ...)">ile_,variable_[,_variable_....html" ;"title="ile_,.html" ;"title=" [file ,"> [file ,variable [, variable ...">ile_,.html" ;"title=" [file ,"> [file ,variable [, variable ...);
write n[( [file][, value [, value ...] )] ;
where * is an optional file variable, which if omitted, defaults to for and , or defaults to for and ; * is a scalar such as a char (character), integer, or real (or for some compilers, certain record types or array types such as strings); and * is a variable or a constant. Example: var f: text; ch: char; n,a,I,B: Integer; S: String; begin Write('Enter name of file to write results: '); readln(s); assign(f,S); rewrite(f); Write('What is your name? '); readln(Input,S); Write('Hello, ',S,'! Enter the number of calculations you want to do:'); writeln(output); Write('? '); readln(N); Write('For each of the ',n,' formulas, enter '); write('two integers separated by one or more spaces'); writeln; for i := 1 to N do begin Write('Enter pair #',i,'? '); read(a,b); READLN; WRITELN(Out,'A ,a,'+ B ,B,'=',A+B); end; close(OUT); end. In the above example, as far as the compiler is concerned, lines 9 and 13 are identical, because if is the file variable being read into by a or statement, the file variable may be omitted. Also, the compiler considers lines 15 and 20 to be identical, because if the file variable being written to is , it can be omitted, which means (on line 20) since there are no arguments being passed to the procedure the parentheses listing arguments can be omitted. Line 26 shows the statement can have any number of arguments, and they can be a quoted string, a variable, or even a formula result. Object Pascal supports ''polymorphic'' procedures and functions, where different procedure(s) or function(s) can have the same name but are distinguished by the arguments supplied to them. Pascal also supports ''default'' arguments, where the value of an argument, if not provided, is given a default value. For the first example, polymorphism, consider the following: function add(a1,a2:integer):Integer; begin add := a1+a2 end; function add(r1,r2:real):real; begin add := a1+a2 end; function add(a1:integer;r2:real):real; begin add := real(a1)+a2 end; function add(r1:real,a2:integer):real; begin add := a1+real(a2) end; In the above example, if as called with two integer values, the function declared on line 1 would be called; if one of the arguments is an integer and one is real, either the function on line 3 or 4 is called depending on which is integer. If both are real, the function on line 2 is called. For default parameters, consider the following: const Three = 3; var K: Integer; function add(i1: integer = 0; i2: integer = 0; i3: integer = 0; i4: integer = 0; i5: integer = 0; i6: integer = 0; i7: integer = 0; i8: integer = 0): integer; begin add := i1+i2+i3+I4+I5+i6+I7+I8; end; begin K := add; K := add(K,1); K := add(1,2); K := add(1,2,Three); end. On Line 6, (and the lines below) the parameter tells the compiler, "if no argument is provided, presume the argument to be zero." On line 19, no arguments were given, so the function returns . On line 20, either a number or a variable can be supplied for any argument, and as shown on line 22, a constant.


In PHP

PHP does not care about types of variadic arguments unless the argument is typed. function sum(...$nums): int echo sum(1, 2, 3); // 6 And typed variadic arguments: function sum(int ...$nums): int echo sum(1, 'a', 3); // TypeError: Argument 2 passed to sum() must be of the type int (since PHP 7.3)


In Python

Python does not care about types of variadic arguments. def foo(a, b, *args): print(args) # args is a tuple (immutable sequence). 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

In Raku, the type of parameters that create variadic functions are known as ''slurpy'' array parameters and they're classified into three groups:


Flattened slurpy

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
. sub foo($a, $b, *@args) foo(1, 2) # [] foo(1, 2, 3) # [3] foo(1, 2, 3, "hello") # [3 "hello"] foo(1, 2, 3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
[6]); # [3, 4, 5, 6]


Unflattened slurpy

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: sub bar($a, $b, **@args) bar(1, 2); # [] bar(1, 2, 3); # [3] bar(1, 2, 3, "hello"); # [3 "hello"] bar(1, 2, 3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
[6]); # [3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...


Contextual slurpy

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). sub zaz($a, $b, +@args) zaz(1, 2); # [] zaz(1, 2, 3); # [3] zaz(1, 2, 3, "hello"); # [3 "hello"] zaz(1, 2,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
; #
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
single argurment fills up array zaz(1, 2, 3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
; # , [4, 5, behaving as **@ zaz(1, 2, 3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
[6]); # [3,
, 5 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
, behaving as **@


In Ruby

Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
does not care about types of variadic arguments. def foo(*args) print args end foo(1) # prints ` > nil` foo(1, 2) # prints `
, 2 The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
> nil`


In Rust

Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...
does not support variadic arguments in functions. Instead, it uses macros. macro_rules! calculate 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.


In Scala

object Program


In Swift

Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
cares about the type of variadic arguments, but the catch-all type is available. func greet(timeOfTheDay: String, names: String...) 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


In Tcl

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. proc greet greet "morning" "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


See also

* Varargs in Java programming language * Variadic macro (C programming language) * Variadic template


Notes


References

{{reflist


External links


Variadic function
Rosetta Code Rosetta Code is a wiki-based programming website with implementations of common algorithms and solutions to various programming problems in many different programming languages. It is named for the Rosetta Stone, which has the same text inscri ...
task showing the implementation of variadic functions in over fifty programming languages.
Variable Argument Functions
— A tutorial on Variable Argument Functions for C++

Subroutines Articles with example Python (programming language) code