return_type function_name( parameter list ) { body of the function }
一個基本的函數(shù)定義由函數(shù)頭和函數(shù)體。這里是一個函數(shù)的所有部分:
Return Type: 函數(shù)可以返回一個值。該return_type是函數(shù)返回值的數(shù)據(jù)類型。有些函數(shù)沒有返回值執(zhí)行所需的操作。在這種情況下,return_type是關鍵字void.
Function Name: 這是函數(shù)的實際名稱。函數(shù)名和參數(shù)列表一起構(gòu)成了函數(shù)簽名。
Parameters: 參數(shù)是像一個占位符。當調(diào)用一個函數(shù),傳遞一個值給該參數(shù)。這個值被稱為實際參數(shù)或參數(shù)。參數(shù)列表是指類型,順序和一個函數(shù)的參數(shù)的數(shù)目。參數(shù)是可選的;也就是說,一個功能可以包含任何參數(shù)。
Function Body: 函數(shù)體包含了定義函數(shù)語句的集合。
我們可以調(diào)用函數(shù)使用下面的語法
function_name(parameter_values)
D編程支持廣泛的函數(shù),它們?nèi)缦旅媪谐觥?/p>
純函數(shù)
拋出異常函數(shù)
參考函數(shù)
自動函數(shù)
可變參數(shù)函數(shù)
inout函數(shù)
屬性函數(shù)
各種函數(shù)功能說明。
純函數(shù)是無法通過他們的論據(jù)訪問全局或靜態(tài)的,可變的狀態(tài)保存函數(shù)。這可以基于一個事實,即一個純函數(shù)是保證變異不被傳遞給它什么,并在情況下,編譯器可以保證純函數(shù)不能改變它的參數(shù),它可以啟用完整,功能純度(啟用優(yōu)化即保證該函數(shù)總是返回相同的結(jié)果為相同的參數(shù))。
import std.stdio; int x = 10; immutable int y = 30; const int* p; pure int purefunc(int i,const char* q,immutable int* s) { //writeln("Simple print"); //cannot call impure function 'writeln' debug writeln("in foo()"); // ok, impure code allowed in debug statement // x = i; // error, modifying global state // i = x; // error, reading mutable global state // i = *p; // error, reading const global state i = y; // ok, reading immutable global state auto myvar = new int; // Can use the new expression: return i; } void main() { writeln("Value returned from pure function : ",purefunc(x,null,null)); }
當我們運行上面的程序,我們會得到下面的輸出。
Value returned from pure function : 30
拋出異常函數(shù)不會拋出從類Exception派生的任何異常。拋出異常函數(shù)是協(xié)變與拋出。
拋出異常保證函數(shù)不發(fā)出任何異常。
import std.stdio; int add(int a, int b) nothrow { //writeln("adding"); This will fail because writeln may throw int result; try { writeln("adding"); // compiles result = a + b; } catch (Exception error) { // catches all exceptions } return result; } void main() { writeln("Added value is ", add(10,20)); }
When we run the above program, we will get the following output.
adding Added value is 30
參考函數(shù)允許函數(shù)按引用返回。這類似于文獻的功能參數(shù)。
import std.stdio; ref int greater(ref int first, ref int second) { return (first > second) ? first : second; } void main() { int a = 1; int b = 2; greater(a, b) += 10; writefln("a: %s, b: %s", a, b); }
當我們運行上面的程序,我們會得到下面的輸出。
a: 1, b: 12
自動功能可以返回任何類型的值。有什么類型的要返回的任何限制。一個簡單的例子功能自動類型如下。
import std.stdio; auto add(int first, double second) { double result = first + second; return result; } void main() { int a = 1; double b = 2.5; writeln("add(a,b) = ", add(a, b)); }
當我們運行上面的程序,我們會得到下面的輸出。
add(a,b) = 3.5
可變參數(shù)函數(shù)是其中一個函數(shù)參數(shù)的數(shù)量,在運行時確定的函數(shù)。在C中,存在具有ATLEAST一個參數(shù)的限制。但在D編程,不存在這樣的限制。一個簡單的例子如下所示。
import std.stdio; import core.vararg; void printargs(int x, ...) { for (int i =上一篇:D語言混合類型下一篇:D語言枚舉Enums