delphi assign to const?
this site : http://www.drbob42.com/delphi/wizards.htm
showed a very puzzling code at the bottom
unit ShareMe开发者_StackOverflow社区m;
{ (c) 1997 by Bob Swart (aka Dr.Bob - http://www.drbob42.com }
interface
const
...
uses
Windows;
const
Handle: THandle = 0;
...
function GetCommandLine: PChar; stdcall;
external 'kernel32.dll' name 'GetCommandLineA';
...
begin
Handle := LoadLibrary('BCBMM.DLL');
end.
how could this be ?
Delphi has something called assignable consts which allows a const value to be assigned. This can be turned on/off through compiler directives and switches. For a longer answer see here.
It sometimes comes in handy in times before class properties were possible. Even if the const is declared inside a function, it keeps its value between calls.
procedure Test;
{$WRITEABLECONST ON}
const
AssignableConst: Integer = 0;
{$WRITEABLECONST OFF}
begin
AssignableConst := AssignableConst + 1;
WriteLn('Test is called ' + IntToStr(AssignableConst) + ' times');
end;
A typed const
, by default (Edit: as noted by Rob in comments, this was changed to no longer be the default years ago), is more like a static variable. You can turn this behavior off with a compiler directive.
This was commonly used as a substitute for class/static properties in old versions of Delphi. Now that Delphi actually has that feature, there is no good reason to do this IMHO.
What you wondering about is a writable typed constant. Typed constants were writable since old days of Turbo Pascal. In the fact, it was the only way to declare an initialized variable. Internally, writable typed constants and initialized variables are equivalent, both go into DATA
segment (thats how Lars Truijens's example work). Also, typed constants can hold data types which disallowed for true constants, what is the true semantic purpose of them. Since Delphi 4 (or 3 even?) Borland figured out what it is weird to mix constants and variables that way, and introduced initialized global variables and $WRITEABLECONST
switch directive (OFF by default). Initialized variables cannot appear in the local scope, thus there is still purpose for writable typed constants to exist.
精彩评论