Interface versus Implementation
Variables declared in the interface section of a unit are truly global and you should limit the number of variables you declare in the interface section especially for reusable units (units that contain classes). Variables declared in the implementation section of a unit have a scope limited to the unit.
Initializing Local Variables
You cannot initialize local variables. The following commented out code, does not work:
procedure TForm2.Button6Click(Sender: TObject);
var
// ButtonClicks: Integer = 0; //Does not work!
begin
end;
Initializing Global Variables
You can initialize global variables but not local variables. Suppose you wish to allow a user to click a button up to 3 times. You can initialize a global variable to track clicks.
The following code does work:
var
ClickCounter: Integer = 0; //Does work!
procedure TForm2.Button7Click(Sender: TObject);
begin
If ButtonClicks >= 3 then
ShowMessage('Stop clicking the button.')
Else
begin
ButtonClicks := ButtonClicks + 1;
Form2.Caption := IntToStr(ButtonClicks);
end;
end;
Instance Counter
Initialized Global Variables and Static Data: Initialized global variables are important for many reasons but I will discuss it's relation to static class data here. Static class data is data of a class that retains state (it's value) whether or not there is an instance of a class. Suppose you wish to have an instance counter. If no classes are currently created, the current value of your instance counter needs to be 0. For each class created, you add 1. For each destroyed, you subtract 1.