Step 1 of 5 · Reading · ~1 min
Learn
Strings, 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. A global array is zero-filled before the program starts; an array declared inside a procedure is not, and FPC will warn Variable "nums" does not seem to be initialized. Don't rely on the difference — say what you mean, with a loop or with FillChar (which lives in the System unit, so it needs no uses):
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…