Functions are generally reusable code blocks that carry out certain instructions in an application. This code block can be called more than once during the application's run time or execution time.
variadic
functions?Variadic functions in D are functions whose parameters are determined at runtime. The number of parameters that can be passed to the function can vary.
variadicFunction(required_parameter1, required_parameter2, ...)
The parameters of variadic functions are put into two categories:
Required parameters: These parameters have to be specified when calling the function. Otherwise, an exception will be raised.
Optional parameters: These are the additional parameters represented by ellipses. They are arbitrary in number.
import std.stdio;import core.vararg;void variadicfunc(int x, ...) {writefln("\t%d", x);for (int i = 0; i < _arguments.length; i++) {if (_arguments[i] == typeid(int)){int j = va_arg!(int)(_argptr);writefln("\t%d", j);}else if (_arguments[i] == typeid(long)){long j = va_arg!(long)(_argptr);writefln("\t%d", j);}else if (_arguments[i] == typeid(double)){double j = va_arg!(double)(_argptr);writefln("\t%g", j);}elseassert(0);}}void main() {variadicfunc(1,2.3, 7L);}
The code above prints all the parameters passed to the function at runtime:
Lines 1–2: We import our required packages to help us work with variadic functions.
Line 4: We declare our variadic function. Notice the ellipses after int x
in the parenthesis ()
. These make it a variadic function.
Line 6: We print our required parameter first since these parameters are not present in the argument list.
Line 8: We use a for
loop to iterate over all the optional parameters passed. We use _arguments.length
to get the number of parameters passed.
Lines 10–27: We check the datatype of each optional parameter and print them accordingly.
Line 31: We call the function and pass any number of parameters that it executes and prints to the screen.