维基副本镜像

这是 pascal.chat 维基的镜像。编辑、历史记录和登录都在那里。

Basic Pascal Tutorial/Chapter 4/Scope/zh CN

English · Français · Български · 中文(中国) · 日本語

4D - 变量作用域 (原作者: Tao Yue, 状态: 未更改)

变量作用域是指变量的使用范围。

全局变量,指在主程序中定义的变量。

它的作用范围:任何子程序可以使用、修改。

过程(函数)中定义的变量如果与全局变量同名,则它是局部变量,即仅在过程(函数)中有效。

这里的要点是:

text
代码块(过程、函数等等)中,变量作用域是,块内定义,块内可见。
pascal
program ScopeDemo;
var A : integer;

  procedure ScopeInner;
  var A : integer;
  begin
    A := 10;
    writeln (A)
  end;

begin (* Main *)
  A := 20;
  writeln (A);
  ScopeInner;
  writeln (A);
end. (* Main *)

程序输出结果是:

text
20
10
20

原因是:

text
定义同名变量多次,如,在主程序、子程序都定义的相同名称的变量,它们调用时,都将调用自己的。

这是一个变量作用域图表,通过块缩进可以很清楚看到变量的使用范围。

上一页 目录 下一页

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.

版本4,最后由WikiArchive于修改。