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

前端 未结 7 1422
眼角桃花
眼角桃花 2021-01-03 20:54

Consider:

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

[Error] file.pas: Constant expression expected
         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 21:33

    I tried this code :

      const
        CAnswer1 = 42;
        CAnswer2 : Integer = 42;
    
      var
        LAnswer : Integer;
    
      begin
        LAnswer := CAnswer1;
        LAnswer := CAnswer2;
      end;
    

    and here is the produced code :

    Project9.dpr.18: LAnswer := CAnswer1;
    004101AC C7056C6E41002A00 mov [$00416e6c],$0000002a //<- assign a hard-coded "42" value
    Project9.dpr.19: LAnswer := CAnswer2;
    004101B6 A1701C4100       mov eax,[$00411c70] //<- fetch a variable's content
    004101BB A36C6E4100       mov [$00416e6c],eax //<- assign this content 
    

    You are right : some constants are more constant than others. The second constant is actually treated by the compiler as a variable.

提交回复
热议问题