D(程式語言)/d2/函式入門
外觀
< D(程式語言)
(重定向自 D(程式語言)/d2/第 3 課)在本課中,你將看到更多關於函式的知識,這些函式在第 1 課中已經使用過。如果你已經熟悉其他類似 C 的語言,你只需要快速瀏覽一下即可。
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!
*/
函式允許你編寫更結構化的程式碼。使用函式,你可以編寫一些程式碼一次,然後在需要使用該程式碼時隨時呼叫它。
讓我們來看看語法
return_type name_of_function(arg1type arg1, arg2type arg2)
{
// function body code here
return something;
}