Jump to content
  • Advertisement
Sign in to follow this  
Spa8nky

Return value for recursive functions not needed but compiler won't accept.

This topic is 2989 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I have a simple recursive function:
        private int Recursive(int a)
        {
            a *= 2;
            if (a < 1000)
            {
                Recursive(a);
                // What should I return here, and why is it needed?
            }
            else
            {
                return a;
            }
        }


Why do I need a return value underneath the recursive function call; it will never be reached?

Share this post


Link to post
Share on other sites
Advertisement
Uh, are you sure you don't mean:

private int Recursive(int a)
{
a *= 2;
if (a < 1000)
{
return Recursive(a);
}
else
{
return a;
}
}

Share this post


Link to post
Share on other sites

private int Recursive(int a)
{
return (a >= 1000) ? a : Recursive(2 * a);
}

This gives different result when a is already >= 1000 at the beginning however ;)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!