+ 2
Alternetive of goto statement?
2 Antworten
+ 3
The most straightforward way would be a do-while loop, since its structure is pretty much the same. So instead of writing
label:
// code
if ( condition ) { goto label; }
you use
do {
// code
} while ( condition);
Similarly to the goto statement, the code inside the loop will be executed at least one time.
Depending on the code, a while loop might also be suitable, or the use of functions.
+ 2
Any of the conditional branching or looping constructs can be used to avoid using goto. Also continue and break are alternatives. In case you are looking for something really esoteric, then learn about setjmp and longjmp. I would not recommend using them, but it is good to be aware of all tools that the language provides.
Here is an example implementation of setjmp/longjmp by Geovanny Martínez Forero:
https://code.sololearn.com/cbaxx13ylwgD/?ref=app
Though his code is in C, the mechanism works also in C++.