calling method inside itself bad?

青春壹個敷衍的年華 提交于 2019-12-24 07:35:28

问题


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


回答1:


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.




回答2:


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();
 }



回答3:


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.



来源:https://stackoverflow.com/questions/19191225/calling-method-inside-itself-bad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!