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

Steve Litt slitt at troubleshooters.com
Mon Jun 12 19:57:15 CEST 2023

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:


>> 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;
>   nextt(1000000000);
>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.


Steve Litt 
Autumn 2022 featured book: Thriving in Tough Times

More information about the fpc-pascal mailing list