6
votes

Delphi allows 3 versions of the Copy function:

function CopyTest(const S: string): string;
begin
  Result:= Copy(S, 1, 5);
  Result:= Copy(S, 1);
//  Result:= Copy(S);   //  not allowed for strings, allowed for dyn arrays
end;

FreePascal seems to compile only the 1st (3-arg) version; for the others I have compile-time error

Error: Wrong number of parameters specified for call to "$fpc_ansistr_copy"

Am I missing some FPC compiler switch or Copy overloads are not available in Free Pascal?

2
Just to add; here's a reference for it. However it doesn't mean it's actual with a current RTL code. - TLama
@TLama - I don't think RTL code matters, the compiler determines what function to call. 'Fpc_Ansistr_Copy' is in astrings.inc anyway, AFAICT there're no overloads to it. - Sertac Akyuz
+1 for noticing a bug. Reported as bugs.freepascal.org/view.php?id=22964 (see comments in Sertac's answer) - Marco van de Voort

2 Answers

6
votes

The 'copy' node generator code is in inline_copy function of pinline.pas of FPC sources. Only for dynamic arrays variants 1 and 3 are valid (which generates code to pass -1 for second and third parameters to fpc_dynarray_copy in case of variant 3). For all other cases (ansi string, wide string, unicode string, char(*) and short string) 3 parameters are required (compiler generates a call to one of the copy functions (e.g. fpc_ansistr_copy in astrings.pas) without checking parameters, since the called function has no overloads or default parameters an exact match of parameters is required). No switches/directives involved.

(*) This one is a bit weird, it returns a shortstring of either itself or ''.

4
votes

As I know the Free Pascal support default value parameters, so there is no need for overloading function. You can writte new Copy function something like...

function Copy(const S: string; From: integer = 1; Count: integer = MaxInt): string;
begin
//There is no need to check the string length
//      if Count > Length(S) then
//        Count := Length(S);
        result := system.Copy(S, From, Count);
end;