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

Started by
2 comments, last by DevFred 14 years ago
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?
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;     }}
Ooops, moment of stupidity. Thanks dude. :)
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 ;)

This topic is closed to new replies.

Advertisement