为什么我可以在没有定义的情况下使用 pascal 中的函数名作为变量名?

Why i can use function name in pascal as variable name without definition?

我想知道 free pascal 函数中非常奇怪的行为,described in docs

据说,下面的代码会compiled/executed成功:

function Test : integer;
begin
  Test := 2;
end;

begin
  WriteLn(Test());
end.

但是如果我在等式右边使用函数名Test,它将执行递归循环。

因此,从一方面来说,pascal 函数使用名称 Test 和函数类型 return 值 integer 定义变量。另一方面,你仍然可以调用函数(使用它的名字进行递归调用)。

为什么?!目标是什么?

在函数体内有一个与函数名相同的特殊变量。它用于保存函数结果。

它是在原始的 Pascal 语法中引入的。后来为了防止不便,引入了另一个名为 Result 的变量,它只是前一个变量的联盟:

Test := 2;
i := Result + 3; // Here i = 5; 

所以,就目前而言,Test := 2;Result := 2; 是一样的。

在等式右边使用函数名的情况下,它被解释为变量,而不是函数调用:

Test := Test + 1; // Increments Test value

但您仍然可以使用括号递归调用函数:

Test := Test() + 1; // Recursion

因此,您可以通过三种方式从函数中 return 取值(以您的示例为例):

function Test : integer;
begin
    Test := 2; // Function result = 2
    Result := 2; // Same to previous
    Exit(2); // Sets function result to 2 end exits immediately
end;

使用哪种方法由您决定。