tags:

views:

160

answers:

3

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

+3  A: 

Yes, and why not?!

filip-fku
+8  A: 

Yes. When you apply static to a function, it's not the same as a static variable within a recursive function (which is a problem).

The former simply controls whether the function is visible outside the compilation unit (for the linker, for example).

The latter means that there's only one copy of the variable for all recursion levels rather than one per recursion level, which is usually what's needed.

So:

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

is okay, 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);
}

is not, since the static variable will be corrupted.

paxdiablo
+2  A: 
#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;
}

So, yes. Note, static storage for i means it retains its value with each call of count_to_five(). However, count_to_five() need not be defined as static.

Its very hard to tell what you're asking.

Tim Post
Tim, why would you answer a question when you've voted to close it as not a real question? That seems a little bizarre - I was going to -1 you for that but it goes against my better nature :-)
paxdiablo
@paxdiablo - I figured out what he was trying to ask _after_ voting to close it, I've since voted to re-open. The question is rather ambiguous.
Tim Post
Yeah, it was a bit of a struggle but no more so than some of the horrors I've tried to help with :-)
paxdiablo
@paxdiablo I'm usually good at figuring out what someone is trying to ask. I originally thought the `why` in the question meant `why would someone want to write a recursive function`. Thanks for taking back the down vote :)
Tim Post