简体   繁体   中英

Why does this recursive function return the wrong value?

I continue to run into an issue in building a recursive function where its returned value is different from the value I expect it to return. I'm fairly certain it relates to the recursive nature of the function, but I don't understand what is happening.

int foo(std::string, int = 0);

int main() {
std::string testString = "testing";
std::cout << foo(testString);
}

int foo(std::string givenString, int numberToReturn) {
    if (givenString.length() == 0) {
        std::cout << "Number to return before actually returning: " << numberToReturn << "\n";
        return numberToReturn;
    }
    if (true) {
        numberToReturn++;
    }
    std::string newString = givenString.erase(0, 1);
    foo(newString, numberToReturn);
}

In this minified example, I have function foo with a string and an int with a default value of 0. Given the string "testing" and no integer, I would expect the recursive function to increment numberToReturn for each call and pass the new value to the next call. This must be partly right because if I cout numberToReturn when I reach the base case, I get the expected value (which in this case it would be 7). But as soon as I return that value, it changes to a much larger number (6422160 in my case).

So with that said, why does the number change on return and how do I prevent that change from happening or otherwise return the correct/expected value?

Edit: For anyone with a similar problem in the future, my issue was that each recusrion call must return something, not just the last one. In my case, returning the last line of function foo solves the issue. Not returning something for every function call leads to undefined behavior.

Your function must always end with return, if it doesn't your function will return some random uninitialised value. For example

int foo( int x )
{
  if ( x == 0 )
  {
    return x;
  }
  foo(x-1);
}

is roughly equivalent to:

int foo( int x )
{
  if ( x == 0 )
  {
    return x;
  }
  foo(x-1);
  return someRandomValue();
}

what you actually want is:

int foo( int x )
{
  if ( x == 0 )
  {
    return x;
  }
  return foo(x-1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM