arraysdelphiconstantsrecord

Constant Expression Expected Error when Initializing Array of Records


I am facing an issue while trying to initialize a constant array of records in Delphi. Here's a simplified version of my code:

  TParameterList = record
    Parm_Name: string;
    Parm_Unit: string;
    IsRequired: Boolean;
    Default_Value: String;
    ParmV: Integer;
    Value_Options: TArray<String>;
  end;

const
 IP_Options: TArray<String> =['Option 1','Option 2','Option 3'];

const
  Cables_Parms: array[0..4] of TParameterList = (
    (Parm_Name: 'Insulation'; Parm_Unit: 'N/A'; IsRequired: True; Value_Options: IP_Options),
    // Other entries...
  );

However, I am encountering the error

Constant expression expected

specifically at the line where I try to initialize Value_Options with IP_Options. I would appreciate any insights into what might be causing this issue and how I can resolve it.


Solution

  • A dynamic array constant cannot be used in a constant expression:

    type
      TTest = record
        a: Integer;
        b: TArray<Integer>;
      end;
    
    const
      Arr: TArray<Integer> = [1, 2, 3];
    
      Test: TTest = (a: 394; b: Arr);       // [dcc32 Error] E2026 Constant expression expected
    

    However, you can use a dynamic array literal in such a context:

    type
      TTest = record
        a: Integer;
        b: TArray<Integer>;
      end;
    
    const
      Test: TTest = (a: 394; b: [1, 2, 3]); // compiles
    

    Obviously, this is not exactly what you may want, but it may be good enough.