Sign in Join
Wiki copytemporary

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

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

OldNewLine
114D - 变量作用域 (原作者: Tao Yue, 状态: 未更改)
22
33*变量作用域*是指变量的使用范围。
44
55全局变量,指在主程序中定义的变量。
66
77它的作用范围:任何子程序可以使用、修改。
88
99过程(函数)中定义的变量如果与全局变量同名,则它是局部变量,即仅在过程(函数)中有效。
1010
1111这里的要点是:
1212
1313`代码块(过程、函数等等)中,变量作用域是,块内定义,块内可见。`
1414
1515``` pascal
1616program ScopeDemo;
1717var A : integer;
1818
1919 procedure ScopeInner;
2020 var A : integer;
2121 begin
2222 A := 10;
2323 writeln (A)
2424 end;
2525
2626begin (* Main *)
2727 A := 20;
2828 writeln (A);
2929 ScopeInner;
3030 writeln (A);
3131end. (* Main *)
3232```
3333
3434程序输出结果是:
3535
3636`20`\
3737`10`\
3838`20`
3939
4040原因是:
4141
4242`定义同名变量多次,如,在主程序、子程序都定义的相同名称的变量,它们调用时,都将调用自己的。`
4343
4444这是一个变量作用域图表,通过块缩进可以很清楚看到变量的使用范围。
4545
46-<figure>
47-<img src="Scope.gif" title="centre" />
48-<figcaption>centre</figcaption>
49-</figure>
46+![](/wiki-images/4/47/Scope.gif)
5047
5148- 所有地方都可以使用全局变量 `A, B, C`。
5249- 然而, 在Alpha过程中新定义了变量A,它将取代全局变量A。
5350- 过程Beta中定义的变量`VCR, Betamax, cassette`,在过程Beta1、函数Beta2都可以使用。
5451- 过程Beta1不能使用函数Beta2定义的变量FailureToo;同理,函数Beta2也不能使用Beta1过程的Failure变量。
5552- 除了Alpha过程可以使用F, G变量,其他地方都不能。
5653- 过程Beta可以调用过程Alpha和Beta。
5754- 函数Beta2可以调用任何子程序,包括自身(主程序不是一个子程序)
5855
5956| | | |
6057|----|----|----|
6158| [[Basic Pascal Tutorial/Chapter 4/Functions/zh CN|上一页]] | [[Basic Pascal Tutorial/Contents/zh CN|目录]] | [[Basic Pascal Tutorial/Chapter 4/Recursion/zh CN|下一页]] |
6259
6360---
6461*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 4/Scope/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