Jump to content

D (The Programming Language)/d2/Intro to Functions

50% developed
From Wikibooks, open books for an open world

Lesson 3: Intro to Functions

[edit | edit source]

In this lesson, you see more of functions, which were used back in Lesson 1. If you are already familiar with another C-like language, you only need to skim this over.

Introductory Code

[edit | edit source]
import std.stdio;

int watch_tv(int first_watched, int then_watched, string channel = "The PHBOS Channel")
{
    writefln("Finished watching %s.", channel);
    return first_watched + then_watched;
}

int commercials(int minutes)
{
    writefln("Watching %s minutes of commercials.", minutes);
    return minutes;
}

int cartoons(int minutes)
{
    writefln("Watching %s minutes of cartoons.", minutes);
    return minutes;
}

void main()
{
    auto minutesoftv = watch_tv(commercials(10), cartoons(30));
    writeln(minutesoftv, " minutes of TV watched!");
}

/*
Output:
  Watching 10 minutes of commercials.
  Watching 30 minutes of cartoons.
  Finished watching The PHBOS Channel.
  40 minutes of TV watched!
*/

Concepts

[edit | edit source]

Functions

[edit | edit source]

Functions allow you to write more organized code. With functions, you can write some code once, and then call it whenever you need to use that code.

Function Syntax

[edit | edit source]

Let's take a look at the syntax:

return_type name_of_function(arg1type arg1, arg2type arg2)
{
    // function body code here
    return something;
}