Scope of Variables

When a variable (or constant) declaration is made, the computer reserves space in memory for storing its value.

The scope of a variable (or constant) is the section of program where a variable's value may be accessed and used.

Global variables exist throughout the run of a program. They are declared at the start of a program and values may be accessed at any time during the run of the program.

Local variables are declared in a subroutine. They are created when the subroutine is started  and only exist for the time the subroutine is run. When the subroutine is completed the memory space reserved for local variables is released for other use.

Note : It is important that variables and constants should be declared locally if possible. This saves memory space when programs are run.

 

 

Example 

Two numbers are input and their product is calculated and output.

This program uses a subroutine (procedure) which draws a line of 20 dashes. This subroutine is called twice from the main program.

(Make sure you fully understand how this program works)

program Product;  
var Num1, Num2,Answer : integer; {GLOBAL variables}
   
procedure DrawLine; {procedure}
var i : integer; {LOCAL variables}
begin    
  for i = 1 to 20 do output('-');  
  output(New line);  
end;   {end of procedure}
   
begin   {Main program starts here}
  output('Please enter first number ');  
  input(Num1);  
  output('Please enter second number ');  
  input(Num2);  
  output(Num1); {formatted to a width of 20}
  output(Num2);  
  DrawLine; {Call procedure}
  Answer := Num1 * Num2; {Calculate answer}
  output(Answer);  
  DrawLine {Call procedure again}
end.