全局变量
全局变量是在函数外部定义的,通常在程序顶部。全局变量将在程序的整个生命周期内保持其值,并且可以在为该程序定义的任何函数中访问它们。一个全局变量可以被任何函数访问。也就是说,在声明之后,全局变量可在整个程序中使用。以下是使用全局和局部变量的示例-
program exGlobal;
var
a, b, c: integer;
procedure display;
var
x, y, z: integer;
begin
(* local variables *)
x := 10;
y := 20;
z := x + y;
(*global variables *)
a := 30;
b:= 40;
c:= a + b;
writeln('Winthin the procedure display');
writeln(' Displaying the global variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
writeln('Displaying the local variables x, y, and z');
writeln('value of x = ', x , ' y = ', y, ' and z = ', z);
end;
begin
a:= 100;
b:= 200;
c:= 300;
writeln('Winthin the program exlocal');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
display();
end.
尝试一下
编译并执行上述代码后,将产生以下结果-
Within the program exlocal
value of a = 100 b = 200 c = 300
Within the procedure display
Displaying the global variables a, b, and c
value of a = 30 b = 40 c = 70
Displaying the local variables x, y, and z
value of x = 10 y = 20 z = 30
请注意,过程显示可以访问变量a,b和c,它们是关于显示的全局变量以及它自己的局部变量。程序的局部变量和全局变量可以具有相同的名称,但函数内局部变量的值将优先。让我们稍微更改前面的示例,现在过程显示的局部变量与a,b,c具有相同的名称-
program exGlobal;
var
a, b, c: integer;
procedure display;
var
a, b, c: integer;
begin
(* local variables *)
a := 10;
b := 20;
c := a + b;
writeln('Winthin the procedure display');
writeln(' Displaying the global variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
writeln('Displaying the local variables a, b, and c');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
end;
begin
a:= 100;
b:= 200;
c:= 300;
writeln('Winthin the program exlocal');
writeln('value of a = ', a , ' b = ', b, ' and c = ', c);
display();
end.
尝试一下
编译并执行上述代码后,将产生以下结果-
Within the program exlocal
value of a = 100 b = 200 c = 300
Within the procedure display
Displaying the global variables a, b, and c
value of a = 10 b = 20 c = 30
Displaying the local variables a, b, and c
value of a = 10 b = 20 c = 30