Procedures and functions, referred to collectively as routines, are self-contained statement blocks that can be called from different locations in a program. A function is a routine that returns a value when it executes. A procedure is a routine that does not return a value.
Function calls, because they return
a value, can be used as expressions in assignments and operations. For example,
I :=
SomeFunction(X);
calls SomeFunction and assigns the
result to I. Function calls cannot appear on the left side of an assignment
statement.
Procedure
calls and, when extended syntax is enabled ({$X+}), function calls can
be used as complete statements. For example,
DoSomething;
calls the DoSomething routine; if DoSomething
is a function, its return value is discarded.
Procedures
and functions can call themselves recursively.
Declaring procedures
and functions
Calling procedures and
functions
Calling procedures and
functions
Declaring procedures and
functions: Overview
过程和函数统称为例程(routines),它们自身包含可以被程序中不同位置调用的语句块。函数(function)是执行时返回值的例程,过程(procedure)是不返回值的例程。
因为函数调用返回值,所以可以在赋值和运算中作为表达式使用。例如,
I :=
SomeFunction(X);
上面的语句调用函数SomeFunction并将结果赋给 I 。函数调用不能出现在赋值语句的左边。
过程调用和扩展语法有效({$X+})时的函数调用可以作为完整的语句使用。例如,
DoSomething;
上面的语句调用DoSomething例程;如果DoSomething是一个函数,那么它返回的值被丢弃。
过程和函数都可以自身递归调用。
编者注
扩展语法编译指示({$X+} 和 {$X-})直接影响函数调用的书写格式。缺省指示是 {$X+} ,此时可以将函数调用用做过程调用;当
{$X-} 有效时,则不能。例如,
function A: Boolean;
begin
Result := False;
end;
function B: Boolean;
begin
Result := True;
end;
...
begin
//缺省为{$X+},因此不必写
A;//合法调用
{$X-}
B;//非法调用,编译器会报告错误信息
end;
此外,当编译指示 {$X+} 有效时,Pascal串可以赋值给形如 array [0..X] of Char 的零基字符数组,并且与字符指针PChar类型兼容,而当编译指示 {$X-} 有效时则不行。与扩展语法有关的详细信息见编译指示:扩展语法(Extended syntax)。