Is there a way to initialize all items in a 2D array in Pascal on one line (without looping)?

126 Views Asked by At

I know that instead of doing the following for a 1D array of Integer, arr,

SetLength(arr, 4);
arr[0] := 11;
arr[1] := 12;
arr[2] := 13;
arr[3] := 13;`

I can also do the above just on one line:

arr := [11, 12, 13, 14];

Now for a 2D array of array of Integer example (with dimensions 2, 2),

arr[0][0] := 11;
arr[0][1] := 12;
arr[1][0] := 13;
arr[1][1] := 14;

Question: Can I also do this on one line something like the following?

arr := [[11, 12], [13, 14]];

Notes:

  • I'm not interested in custom-written functions to "make life easier". I'm strictly asking about default Pascal syntax.
  • I already know how to work with (initialize) 2D arrays in Pascal via looping. If that's the only way, I don't want to waste your time. Just say that's the case.

Because this is a required field, again, I tried arr := [[11, 12], [13, 14]]; but it didn't compile. (Got a Type mismatch error.)

1

There are 1 best solutions below

0
Kai Burghardt On

ISO standard 10206 “Extended Pascal” defines the construct of an initial‑value specifier.

var
    f: array[0..3] of integer value [0: 11; 1: 12; 2, 3: 13];

You can also assign array literals to a variable. Structured value constructors must be prefixed with a data type:

type
    t = array[0..1, 0..1] of integer;
var
    f: t;
begin
    f := t[0: [0: 1; 1: 2]; 1: [0: 3; 1: 4]];

The syntax also provides an otherwise clause for all members not explicitly defined.

var
    f: array[0..9] of real value [5: 12.34; otherwise 56.78];

Special case: If you want to initialize a one‑dimensional array of values in the range 0 through ord(maxChar) in one go, you could specify an adequate string literal. You will then need to apply ord when reading array members.

var
    s: string(8);
begin
    { Beware: The string is silently clipped. }
    s := chr(4) + chr(7) + chr(1) + chr(0) + chr(13) + chr(14) + chr(9) + chr(9)

Obviously this is really “hacky” in nature and not advisable for serious programming. Keep in mind maxChar is an implementation‑defined constant, so not the same value everywhere.