初始化函数重要吗?
Initializing functions important?
老师说函数初始化很重要。我知道你为什么要初始化一个变量,但不明白你为什么要用一个函数来做。
function f(n: integer):integer;
begin
f := 0; //what my teacher wants me to do
Result := n + 1;
end;
在 Delphi 中,函数 Result
未定义,除非您为其设置特定值。所以你总是必须在你的函数中的某个点initialize/set函数Result
。
在您的特定示例中,初始化并不重要,因为只有一个执行路径可以使用 f := n + 1;
设置值
此外,Delphi 编译器可以识别出第一行中分配的值从未被使用,并向您显示警告消息(取决于版本和警告设置):H2077: Value assigned to ‘Result’ never used
function f(n: integer):integer;
begin
Result := 0; // not important because it will be set with next line
Result := n + 1;
end;
在更复杂的函数中,你可以有更多的执行路径,你必须确保每一个都设置函数结果。有时将函数结果预先初始化为某个默认值会更简单、更安全。
function f(n: integer):integer;
begin
Result := 0; // this is important because if n <= 0 Result will be undefined
if n > 0 then Result := n + 1;
end;
当然可以把上面写成
function f(n: integer):integer;
begin
if n > 0 then Result := n + 1
else Result := 0;
end;
不需要预先初始化。但是,有必要为函数中的每个可能执行路径设置函数结果。
另外,使用函数名来设置函数值是过时的技术。最好使用 Result
。
一个重要提示。不同的语言对 returning/seting 函数结果有不同的规则。没有“一个人统治所有人”。请记住,这是非常特定于语言的问题。
老师说函数初始化很重要。我知道你为什么要初始化一个变量,但不明白你为什么要用一个函数来做。
function f(n: integer):integer;
begin
f := 0; //what my teacher wants me to do
Result := n + 1;
end;
在 Delphi 中,函数 Result
未定义,除非您为其设置特定值。所以你总是必须在你的函数中的某个点initialize/set函数Result
。
在您的特定示例中,初始化并不重要,因为只有一个执行路径可以使用 f := n + 1;
此外,Delphi 编译器可以识别出第一行中分配的值从未被使用,并向您显示警告消息(取决于版本和警告设置):H2077: Value assigned to ‘Result’ never used
function f(n: integer):integer;
begin
Result := 0; // not important because it will be set with next line
Result := n + 1;
end;
在更复杂的函数中,你可以有更多的执行路径,你必须确保每一个都设置函数结果。有时将函数结果预先初始化为某个默认值会更简单、更安全。
function f(n: integer):integer;
begin
Result := 0; // this is important because if n <= 0 Result will be undefined
if n > 0 then Result := n + 1;
end;
当然可以把上面写成
function f(n: integer):integer;
begin
if n > 0 then Result := n + 1
else Result := 0;
end;
不需要预先初始化。但是,有必要为函数中的每个可能执行路径设置函数结果。
另外,使用函数名来设置函数值是过时的技术。最好使用 Result
。
一个重要提示。不同的语言对 returning/seting 函数结果有不同的规则。没有“一个人统治所有人”。请记住,这是非常特定于语言的问题。