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

冷暖自知 提交于 2021-01-28 18:50:20

问题


I was wondered about very strange behaviour in free pascal functions, described in docs.

It is said, that following code will be compiled/executed successfully:

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

begin
  WriteLn(Test());
end.

But if i use function name Test in the right side of equation, it will perform recursive loop.

So, pascal functions, from one side, define variable with their name Test and type of function return value integer. From other side, you can still call function (make recursive call using its name).

Why?! What is the goal?


回答1:


Inside function's body there is special variable with name identical to the function name. It used to keep function result.

It was introduced in the original Pascal syntax. Later to prevent inconveniences another variable named Result was introduced and it is just alliance to the previous one:

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

So, for now, Test := 2; and Result := 2; is same.

In case of usage of function name at the right side of equation, it is interpreted as variable, not as function calls:

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

but you still can to call function recursively using brackets:

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

So, you have three ways to return value from the function (for your example):

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;

It is up to you which method to use.



来源:https://stackoverflow.com/questions/34979207/why-i-can-use-function-name-in-pascal-as-variable-name-without-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!