Fabio Vitale
Fabio Vitale

Reputation: 2287

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

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

Upvotes: 11

Views: 11579

Answers (4)

Ebrahim Sabeti
Ebrahim Sabeti

Reputation: 51

This is an example of assign a value to a whole array of integers

const
  C_ARR_COST : array ['a'..'e'] of string = ('01','02','03');
var Conter:Char;
begin
  //Loop
  for Conter := Low(C_ARR_COST) to high(C_ARR_COST) do
    ShowMessage(C_ARR_COST[Conter]);

  //Direct
  ShowMessage(C_ARR_COST['a']);
end;

Good luck.

Upvotes: 0

Arnaud Bouchez
Arnaud Bouchez

Reputation: 43043

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).

Upvotes: 13

Linas
Linas

Reputation: 5545

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;

Upvotes: 13

Uwe Raabe
Uwe Raabe

Reputation: 47758

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.

Upvotes: 3

Related Questions