Pascal - 通过引用调用子程序
将参数传递给子程序的通过引用调用方法将参数的地址复制到形式参数中。 在子程序内部,该地址用于访问调用中使用的实际参数。 这意味着对参数所做的更改会影响传递的参数。
为了通过引用传递参数,Pascal 允许定义变量参数。 这是通过在形式参数前面添加关键字 var 来完成的。 让我们以过程 swap() 为例,该过程交换两个变量中的值并反映调用子程序中的更改。
procedure swap(var x, y: integer); var temp: integer; begin temp := x; x:= y; y := temp; end;
接下来,让我们通过按引用传递值来调用过程swap(),如下例所示 −
program exCallbyRef;
var
a, b : integer;
(*procedure definition *)
procedure swap(var x, y: integer);
var
temp: integer;
begin
temp := x;
x:= y;
y := temp;
end;
begin
a := 100;
b := 200;
writeln('Before swap, value of a : ', a );
writeln('Before swap, value of b : ', b );
(* calling the procedure swap by value *)
swap(a, b);
writeln('After swap, value of a : ', a );
writeln('After swap, value of b : ', b );
end.
当上面的代码被编译并执行时,会产生以下结果 −
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100
这表明现在过程swap()已经更改了调用程序中的值。

