为什么我可以在pascal中将函数名用作没有定义的变量名? [英] Why i can use function name in pascal as variable name without definition?

查看:49
本文介绍了为什么我可以在pascal中将函数名用作没有定义的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对免费的pascal函数(文档中描述的 中描述的行为)感到奇怪.

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.

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

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

因此,pascal函数从一侧定义了变量,其名称为 Test 和函数返回值的类型为 integer .从另一方面来看,您仍然可以调用函数(使用其名称进行递归调用).

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?

推荐答案

在函数体内,有一个特殊变量,其名称与函数名称相同.它用来保持功能结果.

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

它是在最初的Pascal语法中引入的.后来为了避免带来不便,引入了另一个名为 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; 

因此,目前, Test:= 2; Result:= 2; 是相同的.

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.

这篇关于为什么我可以在pascal中将函数名用作没有定义的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆