I have been given an assignment in my CS class to come up with a situation when it would be a good idea to use a goto statement and write a program for it. It can be any situation (though I have to write the program in 3 days) and so far I haven’t thought of anything that couldn’t easily be solved either with recursion or iteration. The only thing that I thought of was Towers of Hanoi, but that can be done in only a few lines with recursion. Do you have any suggestions? Thank you for your help.
EDIT: It has to be the actual goto statement, not other statements that serve the same purpose. For example, the user who answered by suggesting switch, raise, throw, etc, don’t work for the assignment.
This C++ example is arguable:
The problem here is that you must either duplicate the code in the
if()for case 1, or you must duplicate the code for handling case 1. In that example, the handling code was duplicated. See this alternate no-goto solution:Seems fine, except when the duplicated code is something very complicated. Then you start pulling things out into intermediate variables… moving logic away from the place where it’s demanded.
Here’s a solution using
gotowhich doesn’t have compromises:In C++, scope is something to consider.
gotoin C++ is about the only way of jumping around execution with liberal regard to scope.Even if arguable, I still would not use
gotoin the sample I gave, because it complicates the order of execution. Knowing the state of things atcase1:is really not very intuitive.