Loading search index…
No recent searches
No results for "Query here"
Functions are central in D. We’ll learn about functions with a few different examples.
import std.stdio; // Here's a function that takes two ints and returns // their sum as an int. int plus(int a, int b) { // D requires explicit returns, i.e. it won't // automatically return the value of the last // expression. return a + b; } // When you have multiple consecutive parameters of // the same type, you can omit the type name for the // like-typed parameters up to the final parameter that // declares the type. int plusPlus(int a, b, c) { return a + b + c; } void main() { // Call a function just as you'd expect, with // name(args). int res = plus(1, 2); writeln("1+2 = ", res); res = plusPlus(1, 2, 3); writeln("1+2+3 = ", res); }
To run the program, save it as functions.d and use the D compiler:
functions.d
$ dmd -run functions.d 1+2 = 3 1+2+3 = 6
There are several other features to D functions. One is multiple return values, which we’ll look at next.