0

How can I use an index variable for a recursive function that increments every time the function is called so it can return a value without passing it as a parameter or using static or global variables as I want to call this function more than one time not only once.

Here's my code:

bool isAlphabetic(string s)
{
    static int i = 0;
    if (i==s.size())
    {
        return true;
    }
    else if (!isalpha(s[i])){
        return false;
    }
    i++;
    return isAlphabetic(s);
}

Does any body know how to fix this? I know i'm using a static variable but this makes the function run correctly the first time its called but not after that.

5
  • @2501 I don't want to pass it as an argument. is there any possible way to do this than passing an argument? Commented Dec 13, 2014 at 19:41
  • How the heck do you expect to hold status information without storing it somewhere either as a passed-in parameter or in some other variable? Commented Dec 13, 2014 at 19:42
  • What is the behaviour you see and how does it differ from what you expect? Commented Dec 13, 2014 at 19:42
  • @ApprenticeQueue this is a lab assignment and i am required to do this without passing 'i' as a parameter Commented Dec 13, 2014 at 19:45
  • You do not want to pass the position, but you use a string copy on each call. That's MUCH worst, even if the string buffer doesn't get copy each time. Commented Dec 13, 2014 at 19:51

1 Answer 1

4

Worth noting that the recursion may fail with larger strings due to stack overflow.

bool isAlphabetic(const string & s, int pos){
    if(i==s.size()) return true;
    else if(!isalpha(s[pos])) return false;
    return isAlphabetic(s, ++pos);
}

bool isAlphabetic(const string & s){
    return isAlphabetic(s, 0);
}
Sign up to request clarification or add additional context in comments.

3 Comments

A smart compiler would prevent stack overflow because this algorithm is tail-recursive.
Not (necessarily) in debug mode! :)
At least you use a reference to the string which alleviates the horrible copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.