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

Lesson 3: Intro to Functions edit

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

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!");

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

Concepts edit

Functions edit

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

Let's take a look at the syntax:

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