Ilan
Ilan

Reputation: 513

calling method inside itself bad?

I've been coding a text adventure game. On game start, Menu(string Choice, bool takenDump) is called. There are several few other methods that have different scenarios that the user can run into, such as a pokemon encounter and such. If the user dies, then they restart at Menu(), meaning it is called again from within itself. Is there any way to avoid this? Source of program

Upvotes: 1

Views: 7598

Answers (3)

Kenneth
Kenneth

Reputation: 28747

As long as there is a condition to exit the loop, there's no problem. If there's not, you basically have an endless loop (until a StackoverflowException occurs).

From a pure technical point of view, there's no problem as long as you break the loop before a stackoverflowexception occurs.

Upvotes: 4

user622505
user622505

Reputation: 773

One thing you should watch out for when using recursion is stack overflow. It doesn't seem like an issue in what you're trying to do, but in cases where your method calls itself multiple times, and each of those calls call it multiple times again, it will happen (unless you set a reasonable limit of levels of how deep you go). Think fractals, factorials, Fibonacci sequence.

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

No, it is perfectly fine to call method from itself - the name is "recursion" / "recursive function".

In your particular case it is absolutely not necessary (and likely wrong). Top level game code often look like infinite loop rather than recursion:

 while (continuePlaying)
 { 
    ResetLevels_Lives_AndEverything(); 
    while(notDead)
    {
       handleInput()
       draw()
       notDead = ChechStillAlive();
    }
    continuePlaying = CheckContinuePlaying();
 }

Upvotes: 3

Related Questions