views:

98

answers:

3

Dev-cpp comes with an example program Jackpot, which has a GetResults function in it:

void
GetResults ()
{
   .
   .
   .

     else if (i>j)
     {
        cout << "Too BIG\n";
        life = life - 1;    // -1 to the user's "life"
        cout << "Number of remaining life: " << life << "\n\n";
        GetResults();
     }

Is this an elegant way of repeatedly asking for user input? Sure it is more readable than wrapping the ~20 lines around with a do-while loop. I tend to like it but I don't see such a thing often, so I'm not sure. What's your opinion?

EDIT: In your example, recursion depth is prevented by the number of lives, so that seems OK as this won't get bigger than 1000 or even 100 - this is exactly why I have considered it, but now I can see it was a rather stupid idea :) I wonder who put this in an example program...

Thanks for the input guys!

+2  A: 

This will lead to a Stack Overflow for sure, so it shouldn't be done this way! Depends on the stack size how often you can do it, but it sure will crash. In your example, recursion depth is prevented by the number of lives, so that seems OK as this won't get bigger than 1000 or even 100, but you shouldn't use it in general.

I'd also disagree with readability, because indention helps to identify the block inside of a while-loop, but recursion is very uncommon for tasks like this and I think it will often confuse people.

schnaader
+1  A: 

It's not a good method, unless you want to test your application's stack size. ;)

macbirdie
+1  A: 

NO! BAD!

This is not good design at all. The best way would be to wrap it in a while loop at the caller. I.E.

int input = 0;
while (GetInt(&input))
{
    if (input > something)
    {
        cout << "Too big";
        life--;
    }
    else
        break;
}

Ever wonder what a StackOverflow was? Try to input a number too big for a little bit the way that code is written and you will find out :)

nlaq