Is recursion a feature in and of itself?

后端 未结 9 497
陌清茗
陌清茗 2021-01-30 05:49

...or is it just a practice?

I\'m asking this because of an argument with my professor: I lost credit for calling a function recursively on the basis that we did not cov

9条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 06:32

    To answer the literal question, rather than the meta-question: recursion is a feature, in the sense that not all compilers and/or languages necessarily permit it. In practice, it is expected of all (ordinary) modern compilers - and certainly all Java compilers! - but it is not universally true.

    As a contrived example of why recursion might not be supported, consider a compiler that stores the return address for a function in a static location; this might be the case, for example, for a compiler for a microprocessor that does not have a stack.

    For such a compiler, when you call a function like this

    a();
    

    it is implemented as

    move the address of label 1 to variable return_from_a
    jump to label function_a
    label 1
    

    and the definition of a(),

    function a()
    {
       var1 = 5;
       return;
    }
    

    is implemented as

    label function_a
    move 5 to variable var1
    jump to the address stored in variable return_from_a
    

    Hopefully the problem when you try to call a() recursively in such a compiler is obvious; the compiler no longer knows how to return from the outer call, because the return address has been overwritten.

    For the compiler I actually used (late 70s or early 80s, I think) with no support for recursion the problem was slightly more subtle than that: the return address would be stored on the stack, just like in modern compilers, but local variables weren't. (Theoretically this should mean that recursion was possible for functions with no non-static local variables, but I don't remember whether the compiler explicitly supported that or not. It may have needed implicit local variables for some reason.)

    Looking forwards, I can imagine specialized scenarios - heavily parallel systems, perhaps - where not having to provide a stack for every thread could be advantageous, and where therefore recursion is only permitted if the compiler can refactor it into a loop. (Of course the primitive compilers I discuss above were not capable of complicated tasks like refactoring code.)

提交回复
热议问题