Yuriy
Yuriy

Reputation: 257

Is it possible: array in record

I have next arrays

NAMES1: array[0..1] of string = ('NO1','NAME1');
NAMES2: array[0..1] of string = ('NO2','NAME2');

and a record structure

TMyRec = record(
  Name: ????;
);

As result I need to declare a constant array of records like following

const
  StringArraysList: array[0..1] of TMyRec = (
    (Name: NAMES1),
    (Name: NAMES2)
  );

The question is what type should I select for Name in TMyRec?

Upvotes: 1

Views: 3636

Answers (2)

David Heffernan
David Heffernan

Reputation: 613222

You need to do it like this:

type
  TTwoNames = array[0..1] of string;

  TMyRec = record
    Names: TTwoNames;
  end;

const
  StringArraysList: array[0..1] of TMyRec = (
    (Names: ('NO1','NAME1')),
    (Names: ('NO2','NAME2'))
  );

You would prefer to write the final declaration as

const
  NAMES1: TTwoNames = ('NO1','NAME1');
  NAMES2: TTwoNames = ('NO2','NAME2');

  StringArraysList: array[0..1] of TMyRec = (
    (Names: NAMES1),
    (Names: NAMES2)
  );

But that results in

[DCC Error] Unit1.pas(38): E2026 Constant expression expected

Some Delphi constants are not as constant as you would like them to be!

The documentation for record constants states that

The values must be represented by constant expressions.

The documentation for typed constants states that

Typed constants cannot occur in constant expressions.

Put these two rules together and we have E2026.

Upvotes: 11

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58491

You could declare a new type

TName = array[0..1] of string;

and use that in your record declaration. Your declaration then becomes

type
  TName = array[0..1] of string;

  TMyRec = record
    Name: TName;
  end;

const
  StringArraysList: array[0..1] of TMyRec = (
    (Name: ('NO1','NAME1')),
    (Name: ('NO2','NAME2'))
  );

Upvotes: 5

Related Questions