The D programming language is a static typed language, meaning that at each point in time the variables have to be declared with the type indicated. This kind of static typing is also found when writing functions. In this shot, we will see how functions are written and declared in the D programming language.
Functions are language structures that perform simple to complex tasks in a code block and can be used repeatedly in the same program. This program can either be user defined or in-built in the language.
In the D programming language, functions are structurally arranged in the format shown below.
typeOfReturnValue nameOfFunction( parameter) {
function body
}
typeOfReturnValue
: The data type of the function’s return value is declared here. This determines the type of value that the function can return.
nameOfFunction
: This is the identifier given to the function.
parameter
: This is the argument(s), which can be parsed to the function whenever it is called.
function body
: This is where we write what task is to be performed by the function. It can also contain the return
statement, which indicates that the said function should return a value. If we don’t want our function to return any value(s), we will write void
in place of our typeOfReturnValue
as this will cause the function to execute without a return value.
The code below contains two functions. One of these functions is main
, which is usually part of D programs, is used to hold all that is in a particular program, and is void
in this case. The second function is the multiple
function, which has a return value of type integer.
import std.stdio;void main(){int increase = 10;int multiple(int y) {return (y * increase);}int hold = multiple(3);writeln(hold);}
Line 3: We declare the wrapper function main
as void
, which means that it won’t return any value.
Line 4: We define the integer increase
with a value of 10
.
Line 8: We will declare the function multiple
with an integer parameter y
. The function then returns an integer value.
Line 10: The integer value hold
contains the value of the called function multiple
, which is passed an argument of 3
. The output is shown to display, using the std.stdio.writeln
method on line 11.