[chbot] Chchrobotics Digest, Vol 198, Issue 10 GCC and recursion

Charles Manning cdhmanning at gmail.com
Tue Apr 2 21:16:41 BST 2024


Recursion can always be mapped to looping and using a manual stack. Some
languages, such as Fortran, lack recursion and this is how recursive
constructs are achieved.

But back to the original question: gcc certainly handles recursion properly
on ARM, x86 and other "real" CPUs.

But is this gcc generating code for a tiny hobby CPU? If so, it might not
be using a proper stack which would then prevent recursion.

For example on some 8-bitters like 8051, C compilers and stacks do not map
well so, instead, the code that is generated ends up using fixed memory
locations for a fixed "stack". Such constructs do not support recursion.

I would suggest trying out making a small recursive structure such as
factorial and have a look at the generated code.







On Wed, Apr 3, 2024 at 1:30 AM Bevin Brett <bevin_brett at hotmail.com> wrote:

> The alternative to recursion is either a linked list, a fixed size array,
> or a growing array
>
> In RPN evaluation, the code often looks like this, because you don't need
> the full power and cost of recursion
>
> ops : array of operators
> stack : stack of operands
> top = 0
> for op in instructionStream do
>     caseOf nOperands(op.code)
>         alt add:
>             stack[top - 1] += stack[top]
>             top = top - 1
>         alt int:
>             top = top+1
>             stack[top] = op.int
>         ...
>
> Don't forget to check for malformed expressions, which could result in h/w
> stack corruption due to indexing outside 'stack'
>
> /Bevin
>
> ------------------------------
>
> ...
>
> I am building an RPN expression evaluator for the uCPU assembler; I
> can't see any other way to go other than to use recursion to do the
> nested processing that I wish.
>
> Currently using "gcc version 12.2.0 (MinGW-W64 x86_64-ucrt-posix-seh,
> built by Brecht Sanders)"
>
> The first call of the recursed function worked fine, but crashes upon exit.
>
> It could be that the compiler is not generating re-entrant code. The
> only switch I have used is -O0 to disable compiler optimization.
>
> Are there any other switches for GCC that I need to use/be aware of ?
>
> Thanks, Mark
>
> ...
> _______________________________________________
> Chchrobotics mailing list Chchrobotics at lists.ourshack.com
> https://lists.ourshack.com/mailman/listinfo/chchrobotics
> Mail Archives: http://lists.ourshack.com/pipermail/chchrobotics/
> Meetings usually 3rd Monday each month. See http://kiwibots.org for
> venue, directions and dates.
> When replying, please edit your Subject line to reflect new subjects.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ourshack.com/pipermail/chchrobotics/attachments/20240403/a4625f69/attachment.html>


More information about the Chchrobotics mailing list