Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d
variadic functions
communitycreator

What are variadic functions in D?

Chinweuba Elijah Azubuike

What is a function?

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.

What are 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.

Syntax

variadicFunction(required_parameter1, required_parameter2, ...)

Properties of the parameters

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.

Example

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);
      }
      
      else
            assert(0); 
   } 
} 

void main() { 
   variadicfunc(1,2.3, 7L); 
}
D Variadic function

Code explanation

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.

RELATED TAGS

d
variadic functions
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring