A constant is just like a variable (it holds a value) but, unlike a variable, you cannot change the value of a constant.
Delphi Constants
In Delphi, you define constants similar to how you define variables but use the Const keyword instead of the Var keyword. Declare global constants in a unit's interface section and unit constants (scope limited to unit) in the implementation section. Declare local constants above the begin..end block.
Writable Typed Constants
Delphi also supports writable typed constants which are not constants. They are initialized global variables and are a hold-over from earlier versions of Delphi and Turbo Pascal. They are turned off by default in later versions of Delphi so to use them you have to use the compiler directive {$J+} to enable then {$J-} to disable.
Writable Typed Constants Example:
{$J+}
const
clicks : Integer = 1; //not a true constant
{$J-}
begin
Form2.Caption := IntToStr(clicks) ;
clicks := clicks + 1;
end;
Although the Delphi help says not to use writable typed constants, you may find them useful when you wish to use static local variables. You'll have to decide if you wish to use them. The benefit #3 below has over the suggested #1 is that #3 is local and you therefore don't have to worry about duplicate constant/variable names; otherwise, they both work well.
//1. Global variable (suggested technique).
//var
// ButtonClicks: Integer = 0;
procedure TForm2.Button5Click(Sender: TObject);
//2. Does not work (local variable is destroyed with each click
// so the compiler doesn't even allow this to compile).
//var
// ButtonClicks: Integer = 0; //Does not compile!
//3. Writable typed constant is global
// (same as more correct #3 above, but weird).
{$J+}
const
ButtonClicks: Integer = 0;
{$J-}
begin
If ButtonClicks >= 5 then
ShowMessage('Stop clicking the button.')
Else
begin
ButtonClicks := ButtonClicks + 1;
Form2.Caption := IntToStr(ButtonClicks);
end;
end;
The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.