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
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;
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With