private import std.stdio, std.process;
void test(int a, inout int b, out int c)
{
writefln(a);
writefln(b);
writefln(c);
a = 3;
b = 5;
c = 7;
}
void main ()
{
int a = 0, b = 1, c = 2;
test(a, b, c);
assert (a == 0);
assert (b == 5);
assert (c == 7);
std.process.system("pause");
}
在上面的例子里,程序在test函數(shù)中的輸出語(yǔ)句將輸出:
0
1
0
也就是說(shuō),out參數(shù)取值是無(wú)意義的,它只用于賦值。
這里有一個(gè)很大的問(wèn)題,調(diào)用test(a,b,c)時(shí),調(diào)用者對(duì)于c的值被改變可能毫無(wú)知覺(jué),甚至成為隱藏很深的BUG。對(duì)此,許多人建議加強(qiáng)檢查,比如在調(diào)用時(shí),必須指明inout/out:
test(a, inout b, out c);
似乎能夠起到一些警示作用,不過(guò)這樣一來(lái),語(yǔ)法上倒不怎么簡(jiǎn)練了。