C
C#14mo ago
waler

goto vs recursion

Hello, I have a little question about "good habit" in this block of codes. So a little context is, this code will listen to user's input and then do some stuff if some specific key is pressed. However, if none of the specific key is pressed then nothing will happen and the program will keep listening to user's input. This is a code that I have written and due to how I was taught, I used a recursion to loop this method over and over again. However, I also thought about a possibility of using a goto at the very end of the code instead of calling back the Play_Notes method. My question is: Is there a disadvantage to using a "goto" statement here? Since I was taught that goto statements are not recommended.
No description
3 Replies
mtreit
mtreit14mo ago
At first glance, recursion here will eventually stack overflow. I also don't see how goto would be useful. Just write a while (true) loop and break out of the loop when you want to stop. I have a rule to basically never use recursion in production code in c#. I sometimes break that rule but I have to know the depth of recursion has a clear and well defined limit. In functional languages with tail call optimization it's a different story, but c# isn't one of those languages.
JakenVeina
JakenVeina14mo ago
you'd just be using goto to hop back to the beginning, or to hop backwards to several different spots? me personally, I would not shun you for using goto in the latter sense but I would also not do that myself I'd set some kinda state enum and switch on that within a while so, take that info for what you will
waler
walerOP14mo ago
Right, the stack overflow error was something that made me wanted to use the "goto" option as well. But I definitely forgot about a possible while loop here alright, thank you all very much
Want results from more Discord servers?
Add your server