I'm on my PL/x compiler project today and I've added to it some new features such as 'single line comment filter' and 'charcase pre-processor'.
When dealing with comments, I was trying to use a static variable as is defined as 'static' in the C language. But I can't find one in help contents. Then I found one way on the web using compiler directives:
{$J+} typed_const {$J-}
{$WRITEABLECONST ON} typed_const {$WRITEABLECONST OFF}
These compiler directives enable the assignment to the constants. For instance:
procedure StaticVars;
const
{$J+}
iCount: Integer = 0;
{$J-}
begin
Inc(iCount);
ShowMessage(IntToStr(iCount));
end;
Just take care of one thing that the constants declaired should be explicitly typed. Such declairation as "const a=1" will raise a error when compiled even when {$J+/-} is used
.
I'm much confused by this feature provided by Delphi. The constants are declaired in the scope of a procedure, but how can the value assigned to the constant be preserved to next procedure call. I made some experiment on the address of the const/vars. The result shows that the constants are allocated together with global/class variables of the Unit while local vars are still allocated within the scope of the procedure.
I still don't have any idea about this and I couldn't find any better way to implement static var directly or indirectly. I'll be glad to receive your advice.