Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do static variables not allow recursion?

Tags:

c

c#

recursion

As mentioned in Concept of Programming Languages book by Sebesta:

  • Static variables provide global access, can retain values between subprogram invocations (history sensitive), and are efficient.
  • Static variables do not support recursion

Why do static variables not support recursion? Is this because if recursion takes place it will waste a lot of memory because it is static and that means it will not deallocated from memory until the complete program terminates?

like image 363
HATEM EL-AZAB Avatar asked Apr 24 '12 01:04

HATEM EL-AZAB


1 Answers

What makes static fields difficult to use in recursive algorithms is not that they are static but that they are not associated with an activation. Non-static fields are equally difficult to use effectively in a recursive algorithm.

Moreover, the problem is not that it is hard to use fields with recursive algorithms, but more generally that it is hard to use fields with re-entrant algorithms, or algorithms where the same code is going to be called on multiple threads.

What makes local variables and formal parameters useful in recursion and other re-entrancy scenarios is that they are associated with an activation.

In short: the book is confusing because it is too specific. It's like saying that it's difficult to balance a brown egg on a white table; that is true, but what do brown and white have to do with it? It is difficult to balance any egg on any table. It is difficult to correctly use a static field in a recursive call, because it is difficult to correctly use any field in any re-entrancy scenario.

like image 129
Eric Lippert Avatar answered Sep 19 '22 16:09

Eric Lippert