[fpc-pascal] fpc isn't optimised for tail recursion, is it?

Michalis Kamburelis michalis.kambi at gmail.com
Tue Jun 13 01:11:18 CEST 2023


Steve,

If you're looking for equivalent to "return X", use "Exit" with a
parameter in Pascal: "Exit(X)".

It's just a shortcut for "Result := X; Exit;"

Regards,
Michalis

pon., 12 cze 2023 o 19:57 Steve Litt via fpc-pascal
<fpc-pascal at lists.freepascal.org> napisał(a):
>
> Nikolay Nikolov via fpc-pascal said on Mon, 12 Jun 2023 09:15:17 +0300
>
> >On 6/12/23 04:44, Steve Litt via fpc-pascal wrote:
>
> [snip]
>
> >> So, subject to your guidance, I'm assuming FPC isn't optimized for
> >> tail recursion. Is my assumption an accurate one?
> >
> >FPC supports tail recursion optimization, it is enabled at -O2
> >optimization level for most CPUs, however your code isn't eligible for
> >that optimization, because there's extra code, after the recursive
> >invoke. If you change it like that:
> >
> >program recursion_hello;
> >
> >function nextt(num: int64): int64;
> >    begin
> >    writeln('Going deeper=>   ', num);
> >    nextt := num;
> >    if (num > 0) then
> >       begin
> >       nextt(num - 1);
> >       end;
> >    end;
> >
> >begin
> >   nextt(1000000000);
> >end.
> >
> >And if you compile with -O2 it works, without segfaulting (tested with
> >FPC 3.2.2 on x86_64-linux).
>
> Thanks Nickolay,
>
> You're right about not assigning nextt below the call to nextt, and
> about the -O2 argument. After learning from you about -O2 and
> investigating further, I used {$OPTIMIZE tailrec}, which isn't quite the
> same thing, but it worked beautifully. {$OPTIMIZE on} also enables tail
> recursion and speeds things up about 10% of tailrec.
>
> Thanks for your help.
>
> SteveT
>
> Steve Litt
> Autumn 2022 featured book: Thriving in Tough Times
> http://www.troubleshooters.com/bookstore/thrive.htm
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal


More information about the fpc-pascal mailing list