Why do local arrays in functions seem to obstruct TCO?

It looks like the local array in your function prevents tail call optimization on all compilers I checked on:

int foo(int*);

int tco_test() {
    // int arr[5]={1, 2, 3, 4, 5}; // <-- variant 1
    // int* arr = new int[5]; // <-- variant 2
    int x = foo(arr);
    return x > 0 ? tco_test() : x;
}

When variant 1active, there is a true call at the end tco_test()(gcc tries to do some unwrapping earlier, but it still calls the function at the end). Variant 2TCO as expected.

Is there something in local arrays that makes it impossible to optimize tail calls?

+4
source share
1 answer

TCO, foo(arr) . , , , .

, , , ; , .

:

#include <stdio.h>

int *valptr[7], **curptr = valptr, **endptr = valptr + 7;

void reset(void)
{
  curptr = valptr;

}

int record(int *ptr)
{
  if (curptr >= endptr)
    return 1;
  *curptr++ = ptr;
  return 0;
}

int tally(void)
{
  int **pp;
  int count = 0;

  for (pp = valptr; pp < curptr; pp++)
    count += **pp;

  return count;
}

int tail_function(int x)
{
  return record(&x) ? tally() : tail_function(x + 1);
}

int main(void)
{
  printf("tail_function(0) = %d\n", tail_function(0));
  return 0;
}

tail_function recurses, , record x. , 1, tail_function tally . tally .

tally TCO, x. :

int tail_function(int x)
{
tail:
  if (record(&x))
    return tally();
  x = x + 1;
  goto tail;
}

, record , tally 21.

record tally x , , . tail_function ; x.

+4

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


All Articles