views:

124

answers:

2

I was looking at http://stackoverflow.com/q/3780235/71200 and started experimenting. What I discovered is rather interesting.

procedure Clear(AArray: array of Integer);
var
  I: Integer;
begin
  for I := Low(AArray) to High(AArray) do
    AArray[I] := 0;
end;

var
  MyArray: array of Integer;
begin
  Clear(MyArray);
end.

This simple little example shows how you can pass a Dynamic Array to a procedure using an Open Array parameter. It compiles and runs exactly as expected.

procedure Clear(AArray: array of Char);
var
  I: Integer;
begin
  for I := Low(AArray) to High(AArray) do
    AArray[I] := #0;
end;

var
  MyArray: array of Char;
begin
  Clear(MyArray);
end.

Here is nearly identical code the only difference being it is using an array of Char rather than Integer. It does not compile. Instead the compiler spits out:

 E2010 Incompatible types: 'Array' and 'Dynamic array'

Why would this be?

After searching for a while I discovered this QC report. I'm running Delphi 2009 and its still happening.

+1  A: 

I think the reason is that array of Char is compatible with PChar, as this code does compile:

procedure Clear(AArray: array of Char);
var
  I: Integer;
begin
  for I := Low(AArray) to High(AArray) do
    AArray[I] := #0;
end;

var
  MyArray: array of Char;
  P: PChar;
begin
  Clear(P^);
end.

That is probably for historic reasons.
Hopefully Barry Kelly or Danny Thorpe will kick in and provide some more feedback on this.

--jeroen

Jeroen Pluimers
How does `P` know from `MyArray`? Don't cheat with pointers! ;-)
splash
While it compiles, it does not actually work. The procedure has no clue what the high-bound of the PChar is.
Sertac Akyuz
@Sertac: I totally agree it is a bug somewhere; just wanted to point out where it it might come from. Hopefully Barry or Danny will shed some light here.
Jeroen Pluimers
+1  A: 

Since the documentation specifically mentions open array parameters of type Char to be compatible with dynamic arrays, this should be a bug. From 'Open Array Parameters':

function Find(A: array of Char): Integer;
[...]
Note: [...] The previous example creates a function that takes any array of Char elements, including (but not limited to) dynamic arrays. [...]

Sertac Akyuz