Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 4/Parameters/zh CN: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
114B - 参数传递 (原作者: Tao Yue, 状态: 未更改)
22
33参数列表做为过程的一部分,允许传递参数给过程:
44
55``` pascal
66procedure 过程名 (参数组列表);
77```
88
99多个参数组间用分号分隔。
1010
11-```
11+```text
1212参数组1; 参数组2; ... ; 参数组n
1313```
1414
1515参数组格式:
1616
17-```
17+```text
1818标识符1, 标识符2, ... , 标识符n : 数据类型
1919```
2020
2121通过参数传递,以供过程使用这些参数,并且类型都与传递参数的相同。
2222
2323``` pascal
2424procedure Name (a, b : integer; c, d : real);
2525begin
2626 a := 10;
2727 b := 2;
2828 writeln (a, b, c, d)
2929end;
3030```
3131
3232传递参数给过程:
3333
3434``` pascal
3535alpha := 30;
3636Name (alpha, 3, 4, 5);
3737```
3838
3939在主程序中:
4040
41-```
41+```text
4242alpha值为30,之后,传递给过程中的a。
4343```
4444
4545在过程中:
4646
47-```
47+```text
4848a重新赋值为10。实际发生的事情是,变量a和alpha值完全不同。
4949```
5050
5151过程中的a赋值,并没有影响到主程序中的alpha变量。
5252
5353这就是所谓的按值引用。
5454
5555传递参数的另一种方式是按引用传递(按地址传递)。
5656
5757按地址传递参数时,把实参变量的地址传送给被调用过程,形参和实参共用内存的同一地址。在被调用过程中,形参的值一旦改变,相应实参的值也跟着改变。
5858
5959通过在参数组前加VAR关键字,实现按地址参数传递:
6060
6161``` pascal
6262VAR 标识符1, 标识符2, ..., 标识符n : 数据类型;
6363```
6464
6565常量和文本不能做为实际参数,因为它们可能在过程中被改变。
6666
6767下面是*按值*、*按引用*方式传递参数的示例:
6868
6969``` pascal
7070procedure Name (a, b : integer; VAR c, d : integer);
7171begin
7272 c := 3;
7373 a := 5
7474end;
7575
7676begin
7777 alpha := 1;
7878 gamma := 50;
7979 delta := 30;
8080 Name (alpha, 2, gamma, delta);
8181end.
8282```
8383
8484程序运行后,gamma的值是3,因为c是按引用传递过来的参数,
8585
8686alpha的值是1,因为它是按值传递过来的参数,看起来有点混乱。
8787
8888按值传递参数,会复制一份传递过来的值,供过程使用。作用域只在过程中。
8989
9090按地址传递参数,会使用同一变量值,相当于建立映射在同一内存地址。赋值操作会影响到外部对应变量。
9191
9292按句话说: 按值传递参数,是单向的:主程序至过程。 按地址传递参数,是双向的。
9393
9494| | | |
9595|----|----|----|
9696| [[Basic Pascal Tutorial/Chapter 4/Procedures/zh CN|上一页]] | [[Basic Pascal Tutorial/Contents/zh CN|目录]] | [[Basic Pascal Tutorial/Chapter 4/Functions/zh CN|下一页]] |
9797
9898---
9999*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Parameters/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history