delphiconstantscompiler-errorsdelphi-5compile-time-constant

Delphi: All constants are constant, but some are more constant than others?


Consider this:

const 
  clHotlight: TColor = $00FF9933;
  clLink = clHotLight; //alias of clHotlight

[Error] file.pas: Constant expression expected

The alternate wording that works:

const 
  clHotlight = TColor($00FF9933);
  clLink = clHotLight; //alias of clHotlight

Please explain.


Then consider this:

const 
  AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
  SuperuserGUID = AdministratorGUID; //alias of AdministratorGUID

[Error] file.pas: Constant expression expected

And the fix.

Edit: Added keyword const before declarations; someone didn't believe they were const.


Solution

  • clHotlight: TColor = $00FF9933; is not a constant but a typed constant (=static variable), i.e. the compiler reserves a slot in memory for a TColor which will hold the value $00FF9933 initially at run time.
    Because that value can be changed later (with the Assignable Const option ON), it is not a real constant and cannot be accepted by the compiler in clLink = clHotLight;

    clHotlight = TColor($00FF9933); is strictly the same as clHotlight = $00FF9933;
    It is a true constant and the compiler will replace clHotlight by its value $00FF9933 wherever it appears in the code. And for clLink as well.

    Read on this SO question (In Delphi 7, why can I assign a value to a const?) and all the good answers there...

    EDIT: about TGUID...
    The problem is that writing AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}'; is not proper.
    It is using some compiler magic to call StringToGUID behind the scene, allowing the convenience to express the GUID as a string which they are not by nature. They are records.

    So, trying AdministratorGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}'; will not work. That is not a GUID...

    A workaround is to have a typed constant and variables pointing to the same memory area using the absolute directive:

    const
       AdministratorGUID: TGUID = '{DE44EEA0-6712-11D4-ADD4-0006295717DA}';
    var
       SuperuserGUID: TGUID absolute AdministratorGUID; //alias of AdministratorGUID
       RootGUID: TGUID absolute AdministratorGUID;      //alias of AdministratorGUID