Variadic Functions

Learn about the variadic functions of D in this lesson.

Despite appearances, default parameter values do not change the number of parameters that a function receives. For example, even though some parameters may be assigned their default values, the printAA() function always takes four parameters and uses them according to its implementation:

void printAA(string title, 
             string[string] aa,
             string keySeparator = ": ",
             string elementSeparator = ", ")

On the other hand, variadic functions can be called with an unspecified number of arguments. We have already been taking advantage of this feature with functions like writeln(). writeln() can be called with any number of arguments:

writeln( "hello", 7, "world", 9.8 // and any number of other arguments as needed );

How to define variadic functions

There are four ways of defining variadic functions in D:

  • The feature that works only for functions that are marked as extern(C). This feature defines the hidden _argptr variable that is used for accessing the parameters. This course does not cover this feature partly because it is unsafe.

  • The feature that works with regular D functions, which also uses the hidden _argptr variable, and the _arguments variable, the latter being of type TypeInfo[]. This course does not cover this feature either, both because it relies on pointers, which have not been covered yet, and because this feature can be used in unsafe ways as well.

  • A safe feature with the limitation that the unspecified number of parameters must all be of the same type. This is the feature that is covered in this section.

  • An unspecified number of template parameters

Passing parameters to variadic functions

The parameters of variadic functions are passed to the function as a slice. Variadic functions are defined by a single parameter of a specific type of slice followed immediately by the ... characters:

Get hands-on with 1200+ tech skills courses.