Skip to content
Static Arrays
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings, Arrays, Types

Pascal static arrays have their size fixed at compile time. Indices can be ANY ordinal range — not just 0..N-1.

var
    nums: array[1..10] of integer;     { 1-indexed }
    grades: array[1..5] of char;
    days: array['A'..'Z'] of integer;  { char-indexed (rare but legal) }
begin
    nums[1] := 100;
    grades[1] := 'A';
end.

Multi-dimensional:

var
    matrix: array[1..3, 1..3] of integer;
begin
    matrix[2, 3] := 42;
end.

Initialization — Pascal arrays don't auto-zero like C/Go. Use a loop or use FillChar:

uses SysUtils;
FillChar(nums, SizeOf(nums), 0);    { all zeros }

Low() and High() are your friends — adapt to any range:

for i := Low(nums) to High(nums) do
    nums[i] := 0;

Using 1 and Length(nums) would lock you into a 1-indexed array; Low/High adapts to whatever bounds the array has.

Array constants:

const
    days: array[1..7] of string =
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');

Open-array parameters — pass any-sized array to a function:

function Sum(a: array of integer): int64;
var i: integer;
begin
    Result := 0;
    for i := Low(a) to High(a) do
        Result := Result + a[i];
end;

{ Caller — array constructor: }
WriteLn(Sum([1, 2, 3, 4, 5]));

Inside the function, the array is always 0-indexed (open-array convention).

Static vs dynamic (covered in Intermediate):

  • Static: size at compile time, faster, can have non-zero start index
  • Dynamic: size at runtime via SetLength, always 0-indexed

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…