Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assign a value to a whole array of integers?

Tags:

delphi

I know I can do that:

const
  arrayOfIntegers : Array[1..15] of Integer = (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);

But how can I do the following instead?

var
  arrayOfIntegers : Array[1..15] of Integer;
begin
  arrayOfIntegers := (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);
end;

As soon as I try to compile the code above I get E2029 ')' expected but ',' found

like image 920
Fabio Vitale Avatar asked Nov 21 '11 11:11

Fabio Vitale


3 Answers

You didn't mention what Delphi version you're using but in the modern Delphi you can do something like this:

var
  arrayOfIntegers : TArray<Integer>;
begin
  arrayOfIntegers := TArray<Integer>.Create(3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);
end;
like image 63
Linas Avatar answered Sep 23 '22 07:09

Linas


A typical use will be the following:

type
  TIntegerArray1to15 = Array[1..15] of Integer;
const
  INIT_INT_1_15_ARRAY: TIntegerArray1to15 = (3,2,8,10,1,6,2,13,13,3,13,13,13,3,45);

var
  arrayOfIntegers : TIntegerArray1to15;
begin
  arrayOfIntegers := INIT_INT_1_15_ARRAY;
  .... use and update arrayOfIntegers[]
end;

You should better define your own type in this case (code won't be slower or bigger, and you'll be able to make assignments between instances of this type). And you'll ensure that your array boundaries will be as expected (1..15).

The const statement will be compiled as a "reference" array, which will be copied in your arrayOfIntegers local variable. I've made it uppercase, which a somewhat commmon usage when declaring constants (but not mandatory - this is just a personal taste).

If you want your code to be more generic and reusable (which IMHO makes sense if you want to be a lazy programmer) you may rely on dynamic arrays, and/or array of const parameters (if your array start with index 0).

like image 23
Arnaud Bouchez Avatar answered Sep 22 '22 07:09

Arnaud Bouchez


The syntax used in the const section is only valid for typed array constants. You cannot use it as a literal array constant in an assignment.

like image 44
Uwe Raabe Avatar answered Sep 25 '22 07:09

Uwe Raabe