Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Control Flow and Functions

Functions in D: Parameters, Return Values and Attributes

Define and call D functions, pass arguments by value or by ref, use default and in/out parameters, return multiple values with tuples, and apply attributes like pure and nothrow.

A function packages a piece of work under a name so you can reuse it. D functions look like C functions but come with several upgrades: default arguments, ref and in parameters that say how data is shared, type inference for return values, nested functions, and attributes such as pure and nothrow that let the compiler verify properties of your code. This lesson covers all of them. Listings are read-only; the C stand-ins show the matching calling conventions.

Defining and calling

D
import std.stdio;

int add(int a, int b)
{
    return a + b;
}

void greet(string name = "world")     // default argument
{
    writeln("Hello, ", name, "!");
}

void main()
{
    writeln(add(2, 3));    // 5
    greet();               // Hello, world!
    greet("Ada");          // Hello, Ada!
}

The syntax is ReturnType name(parameters) { body }. A function with no value to return has the return type void. Parameters with defaults must come last. A function can also be declared with auto return type, letting the compiler deduce it:

D
auto square(int x) { return x * x; }     // returns int

For one-line functions there is the expression body int twice(int x) => x * 2;.

How arguments are passed

By default, arguments are passed by value: the function gets a copy, so changing it does not affect the caller. Storage classes change that:

Keyword Effect
(none) Copy of the value
ref Alias to the caller's variable: changes are visible, and the argument must be an lvalue
in Read-only input (a modern, preferred form of const)
out Output parameter: reset to its .init on entry, caller sees the result
lazy Evaluated only if and when the function uses it
D
import std.stdio;

void incrementAll(ref int[] values)      // ref: the slice variable itself can change
{
    foreach (ref v; values)
    {
        ++v;
    }
}

void divide(int a, int b, out int quotient, out int remainder)
{
    quotient = a / b;
    remainder = a % b;
}

void main()
{
    int[] nums = [1, 2, 3];
    incrementAll(nums);
    writeln(nums);                       // [2, 3, 4]

    int q, r;
    divide(17, 5, q, r);
    writeln(q, " ", r);                  // 3 2
}

Array and slice arguments are small (pointer plus length), so passing them by value is cheap, and the elements they point to are shared: a function that writes values[0] = 9 changes the caller's data even without ref. ref on a slice parameter matters only when you want to change the slice itself (for example to append and have the caller see the new length).

Returning more than one value

Use an out parameter, a struct, or a tuple from std.typecons:

D
import std.typecons : tuple, Tuple;
import std.stdio;

auto minMax(int[] data)
{
    int lo = data[0], hi = data[0];
    foreach (v; data)
    {
        if (v < lo) lo = v;
        if (v > hi) hi = v;
    }
    return tuple(lo, hi);
}

void main()
{
    auto result = minMax([4, 9, 1, 7]);
    writeln(result[0], " ", result[1]);   // 1 9
    auto t = tuple!("low", "high")(1, 9);
    writeln(t.low, " ", t.high);          // 1 9
}

Return by ref and lazy arguments

A function can return a reference when it is marked ref, making f(x) = 5 assign through it. And lazy delays an expensive argument:

D
bool logWhenDebug(bool debugOn, lazy string message)
{
    if (debugOn)
    {
        writeln(message);      // message is only built when used
    }
    return debugOn;
}

If debugOn is false, the string expression is never evaluated.

Attributes: promises the compiler checks

You can annotate a function with attributes, and the compiler rejects any code that breaks the promise:

  • pure: no access to mutable global state; the same inputs give the same output (helps optimization and reasoning).
  • nothrow: guarantees no exception escapes.
  • @nogc: guarantees no garbage-collected allocation (important for real-time code).
  • @safe: forbids memory-unsafe operations such as arbitrary pointer arithmetic and unchecked casts.
  • const/immutable on methods, covered in the classes chapter.
D
int safeAdd(int a, int b) pure nothrow @nogc @safe
{
    return a + b;
}

Templates infer these attributes automatically, so generic code stays flexible. Nested functions can live inside other functions and use their local variables: int main() { int base = 10; int addBase(int x) { return x + base; } return addBase(5); }.

C stand-ins for argument passing

C has no ref, but a pointer does the same job. These stand-ins match D's out, ref and tuple-like returns.

C C stand-in: out parameters through pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is 3 2, then 2 3 4, matching the D listing.

C C stand-in: returning a pair like a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 1 9. A D tuple(lo, hi) is this struct generated for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the ref storage class do on a parameter?

    Changes to a ref parameter are visible to the caller.
  2. 2. Which parameter class is reset to its default value on entry?

    out parameters are set to their .init before the body runs.
  3. 3. What does the pure attribute promise?

    pure functions depend only on their parameters.
  4. 4. When is a lazy argument evaluated?

    lazy delays evaluation to the point of use, each time.

Summary

  • Functions take parameters by value by default; ref, in, out and lazy change how.
  • Default arguments, auto returns, expression bodies and nested functions reduce boilerplate.
  • Return several values with out, structs or tuple.
  • Attributes (pure, nothrow, @nogc, @safe) are checked promises.

Next: Function features: UFCS, lambdas and delegates