Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Function

Part of TutorialFundamentals

Description

Using a function, you can code it once and then call it when you need it, wherever you need it. The code demonstrates that you can assign the return value of a function to a variable. You may also use the return value of a function as an argument to another function (in this case squareIt(i) is evaluated in the for loop, and it's return value is passed to the writefln() function).

Example

import std.stdio;

uint squareIt(uint x) 
{
    return x * x;
}

void main() 
{
    uint num = 10;
    writefln("%s squared is: %s\n", num, squareIt(num));
    
    num = squareIt(20);
    writefln("20 squared is: %s\n", num);
    
    for (int i = 0; i <= 5; i++)
    {
        writefln("(%s * %s) == %s", i, i, squareIt(i));
    }
}

Source

Based on function.html by jcc7.