Why can't languages ​​like C, Pascal implement tail recursion?

I read SICP . One footnote states that:

Creating a compiler to generate tail recursive code might seem like a simple idea. But most compilers for common languages, including C and Pascal, do not, and therefore these languages ​​cannot represent iterative processes only in terms of the procedure. The difficulty with tail recursion in these languages ​​is that their implementations use the stack to store procedure arguments and local variables, as well as return addresses.


I cannot understand why it is impossible to implement tail recursion if the stack is used for procedure arguments, local variables and return addresses.

+4
source share
2 answers

The difficulty with tail recursion in these languages ​​is that their implementations use the stack to store procedure arguments and local variables, as well as return addresses.

There are no function calls in machine language, so function calls are translated into

  • Putting arguments on the call stack
  • push stack return address
  • go to the body of the routine you want to call
  • when the routine completes, it returns to the return address that we pushed onto the stack earlier
  • arguments are removed from the stack

" ", , 5 ( ). C, , . , printf ( ), , , "" - , ( ). , , , , TCO.

+7

C, , . C :

int foo (int bar)
{
    int baz;
    ...
    return foo(baz);
}

C . ( ) , , (gcc, MSVC clang/LLVM):

Pascal, pascal, LLVM, 2004 :

, LLVM , , , , C, , , , , , .

:

, , , .

, . , , (, ), , . , , , 32- , . , , , .

+9

Source: https://habr.com/ru/post/1568569/


All Articles