One function has already been introduced: main()
- the starting point of every
D program. A function may return a value (or be declared with
void
if nothing is returned) and accept an arbitrary number of arguments:
int add(int lhs, int rhs) {
return lhs + rhs;
}
auto
return typesIf the return type is defined as auto
, the D compiler infers the return
type automatically. Hence multiple return
statements must return values with
compatible types.
auto add(int lhs, int rhs) { // returns `int`
return lhs + rhs;
}
auto lessOrEqual(int lhs, int rhs) { // returns `double`
if (lhs <= rhs)
return 0;
else
return 1.0;
}
Functions may optionally define default arguments. This avoids the tedious work of declaring redundant overloads.
void plot(string msg, string color = "red") {
...
}
plot("D rocks");
plot("D rocks", "blue");
Once a default argument has been specified, all following arguments must be default arguments too.
Functions may even be declared inside other functions, where they may be used locally and aren't visible to the outside world. These functions can even have access to objects that are local to the parent's scope:
void fun() {
int local = 10;
int fun_secret() {
local++; // that's legal
}
...
Such nested functions are called delegates, and they will be explained in more depth soon.