Is recursion possible in a static function?

Is it possible to write a recursive static function in C?

+3
source share
3 answers

Yes. When you apply staticto a function, it is not the same as a static variable in a recursive function (which is the problem).

The first simply controls whether the function will be visible outside the compilation unit (for example, for the linker).

The latter means that there is only one copy of the variable for all levels of recursion, and not one at the recursion level, which is usually necessary.

So:

static unsigned int fact (unsigned int n) {
    if (n == 1U) return 1;
    return n * fact (n-1);
}

ok but:

static unsigned int fact (unsigned int n) {
    static unsigned int local_n; // would be fine if not static!
    local_n = n;
    if (local_n == 1U) return 1;
    return local_n * fact (local_n-1);
}

no, as the static variable will be corrupted.

+13
source

Yes, and why not ?!

+3
source
#include <stdio.h>

static void count_to_five(void)
{
   static int i = 0;

   while (i < 5) {
     i++;
     printf("%d\n", i);
     count_to_five();
   }

  puts("You are seeing this because I counted to five! (did not enter loop)\n");    
  return;
}

int main(void)
{
    count_to_five();
    return 0;
}

, . . i , count_to_five(). count_to_five() static.

, .

+3

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


All Articles