Jump to content

[PASCAL] Local Variables


CouldnoT
 Share

Recommended Posts

Local Variables

 

We can define variables locally inside a procedure or function to be used only inside its code. These variables can not be accessed from the main application's code or from other procedures and functions.

 

Example:

 

procedure Loop(Counter: Integer);
var
 i: Integer;
 Sum: Integer;
begin
 Sum:= 0;
 for i:= 1 to Counter do
 Sum:= Sum + i;
 Writeln('Summation of ', Counter, ' numbers is: ', Sum);
end;
begin // Main program section
 Loop;
 Write('Press enter key to close');
 Readln;
end.

 

In the procedure Loop, there are two local variables Sum and I. Local variables are stored in Stack memory, which is a part of memory that allocates variables temporarily until the procedure's execution is finished. That means it will be unaccessible and can be overwritten when program execution reaches this line of code:

 

  Write('Press enter key to close');

 

Global variables can be accessed from the main program and other procedures and functions. They can hold values until the application is closed, but this can break the structure of the program and make it hard to trace errors, because any procedure can change global variable values, which may result in unknown values and misbehavior when we forget to initialize them.

 

Defining local variables guarantees their privacy, which helps the procedures and functions to be ported or called from anywhere without worry about global variables values.

 

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.