do {
// Attempt to set a value here, but maybe not
// succeed
// Like asking a user for a specific set of values
...
if(choice == sane) break;
// User did bad. Try again.
} while(false);
Sometimes, you need a way to repeatedly call the same unique piece of code until it becomes something valid.However, goto serves it, and does it in a much clearer way, in my opinion:
try_sane:
// Attempt to set value
...
if(choice == sane) goto sane;
// Nope. Try again.
goto: try_sane
sane:
printf("%s\n", "Well done.");Yes, with a single check, you might as well just do "if" instead. The actual code involved numerous such checks. Think of code that repeatedly calls various APIs that return error codes; if any call returns a non-success code, the code must immediately exit this block. You can just keep writing nested ifs, but then you start getting crazy nesting levels after a few calls, which makes code pretty hard to read. So, most people prefer to just jump out instead, resulting in a flat code on the success path, with all errors handled with jumps.
In C or C-like C++ (sans exceptions), this idiom is extremely common, and usually it's done with "if .. goto error" or something similar, often wrapped in a macro.
Are there more complex examples where this becomes if-else hell?