Home > database >  How to initialize array in Pascal using type?
How to initialize array in Pascal using type?

Time:04-12

For the sake of fun, I'd like to refresh my Pascal knowledge, so gotta review the basics again.

Let's see this Java code:

class ArrayTest {

    public static void main(String args[]){
        int[] numArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    }
}

Rewrite that into Pascal:

type
    arrNum = array[1..10] of integer;
var
    BBB: arrNum;

begin
    BBB := [1,2,3,4,5,6,7,8,8,10];
end.

Compiling the code with FPC 3.2.2 on MacOS, the result is:

arrnum.pas(7,12) Error: Incompatible types: got "{Array Of Const/Constant Open} Array > of ShortInt" expected "arrNum"

arrnum.pas(10) Fatal: There were 1 errors compiling module, stopping

Fatal: Compilation aborted Error: /usr/local/bin/ppcx64 returned an error exitcode

What's wrong here?

CodePudding user response:

A similar syntax using a constructor is available for dynamic arrays (BBB), but not for static ones. Static initializations can be done by assigning a type constant to a variable (BB10:=CCC10) or by defining an initialized constant(DDD10).

The below code demonstrates some cases:

{$mode delphi} 
type
    arrNum = array of integer;
    arrNum10 = array[0..9] of integer;

const CCC10 : arrNum10 = (1,2,3,4,5,6,7,8,9,10);
var
    BBB: arrNum;
    BBB10 : arrNum10;


    DDD10  : arrnum10 = (1,2,3,4,5,6,7,8,9,10);

begin
    BBB := ArrNum.Create(1,2,3,4,5,6,7,8,8,10);
    BBB10:=CCC10;
end.

CodePudding user response:

If you declare as an array you should use a for loop to init

type
    arrNum = array [ 1..10] of integer;
var
    BBB: arrNum;
    i: integer;

begin
    for i:=1 to 10 do
    BBB[i] := i;
end.

CodePudding user response:

You can initialize it in the declaration:

program ideone;
type
    arrNum = array[1..10] of integer;
var
    BBB: arrNum = (1,2,3,4,5,6,7,8,8,10);
    i: Integer;
begin
    for i := 1 to 10 do
        Write(BBB[i])
end.

CodePudding user response:

In Pascal [1, 2, 3, 4, 5, 6, 7, 8, 8, 10] is a set literal containing 9 distinct integer values. You cannot assign sets to an array data type variable.

Instead you will need to specify an array literal and properly denote it, like so:

arrNum[1: 1; 2: 2; 3: 3; 4: 4; 5: 5; 6: 6; 7: 7; 8: 8; 9: 8; 10: 10]

However, as of version 3.2.0 the FPC does not (yet) comply with the Extended Pascal specification (ISO standard 10206). They brewed up their own Pascal, so the compiler (“mis‑”)identifies your set literal as an “{Array Of Const/Constant Open} Array of ShortInt”. See Marco’s answer how to initialize “dynamic arrays” as an alternative.

  • Related