Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are recursive functions re-entrant

I have seen many recursive functions(mostly used in computing some mathematical operations e.g. factorial, sum of the digits in a number, etc...) which involve use of a static variable which holds the result of the each recursive call/operation, and uses it for the subsequent calls.

So does that make recursive functions non-rentrant and not thread-safe.

Are there other use-cases of recursive functions which does not need static variables?

like image 397
goldenmean Avatar asked Jul 11 '26 00:07

goldenmean


2 Answers

The two are different concepts. One does not imply the other, or vice versa.

For instance, is this a recursive function (hypothetical language)?

global sum = 0

proc accumulate(treeNode)
    sum += treeNode.Value
    if treeNode.Left then accumulate(treeNode.Left)
    if treeNode.Right then accumulate(treeNode.Right)
end

Obviously it is a recursive function, but it is not reentrant, due to the use of the global variable. By "global" here, at the very least I mean "not local to the function".

However, this is a bad example, since it is very easy to make it not rely on the global variable at all, by simply returning the sum:

func accumulate(treeNode)
    sum = treeNode.Value
    if treeNode.Left then sum += accumulate(treeNode.Left)
    if treeNode.Right then sum += accumulate(treeNode.Right)
    return sum
end

There is nothing inherent in the concept of a recursive function that makes it non-threadsafe or reentrant, or the opposite, it all depends on what you actually write in the function in question.

like image 197
Lasse V. Karlsen Avatar answered Jul 13 '26 16:07

Lasse V. Karlsen


Are there other use-cases of recursive functions which does not need static variables.?

Of course. In fact, static variables in recursive functions should be the exception, not the rule:

I have seen many recursive functions(mostly used in computing some mathematical operations e.g. factorial, sum of the digits in a number, etc...) which involve use of a static variable which holds the result of the each recursive call/operation, and uses it for the subsequent calls.

Those were quite frankly bad implementations. Static variables are absolutely not needed here. They probably served as accumulators; this can be done better by passing the accumulator around as an extra argument.

like image 37
Konrad Rudolph Avatar answered Jul 13 '26 16:07

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!