Thread: Recursion and variables

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    4

    Recursion and variables

    Hey,
    I have a function that calls itself recursively, and stores its results in a static array or structs.
    The function itself works fine, however, when the function isn't called recursively, the array needs to be null'd, right now my solution to this is something like:
    Code:
    fooStruct **foo(char *c, int new){
    . . .
    static fooStruct **strct = NULL;
    . . .
    if(new)
        strct = NULL;
    And when calling the function from any other function, passing '1' as the second argument, and when calling the function recursively, passing '0'

    This works, but feels and looks strange. I'm wondering if there is a more elegant solution to this problem?

    Thanks in advance.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I think the more elegant solution might be:
    Code:
    fooStruct **foo(char *c) {
        fooStruct **strct = fooHelper(c, NULL);
        return strct;
    }
    where fooHelper contains the previous recursive code, and instead of a static pointer we pass it in as the second argument. And now the calling code doesn't need to know anything about this mysterious second argument.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    4
    Perfect!
    That works great.
    Thanks for the speedy reply!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recursion
    By jordan_230 in forum C Programming
    Replies: 0
    Last Post: 11-09-2008, 04:02 PM
  2. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  3. Recursive function crashes.
    By samus250 in forum C Programming
    Replies: 9
    Last Post: 01-16-2008, 02:58 PM
  4. recursion
    By cerin in forum C++ Programming
    Replies: 19
    Last Post: 02-21-2005, 06:59 PM
  5. STL list recursion
    By evader in forum C++ Programming
    Replies: 4
    Last Post: 01-11-2004, 04:54 AM