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

Nested Functions

Part of TutorialFundamentals


Nested functions allows you to structure functions in a clever way if that's how your mind works.


import std.stdio;

int addSquares(int a, int b)
    int squareIt()
        return (a * a) + (b * b);
    return squareIt();

void main() 
    writeln(addSquares(2, 2));

How it works

The squareIt() function is a nested function inside the addSquares() function. A nested function in D has access to its enclosing function scope, which means it can use any variables declared inside addSquares() as well as its parameters (a special case is when squareIt is defined as a static function, see the static section in the link on the bottom of this page).

In the return squareIt(); statement, the squareIt() function is evaluated, which in this case gives the result 8. The return statement then returns the value 8 which is used as the argument to the writeln() function.

More Information

See also the D Specification.