by int_19h · 8y ago · 0 comments
do {
...
if (...) break;
...
} while (false);
It took me a while to realize what this was about. But, basically, he invented a way to goto (so long as it was forward) without actually spelling it out. When I asked him, he gave the usual creed about how "goto is bad", and wouldn't be convinced that break is goto, especially given how he used it.Needless to say, this kind of code is actually less readable than if it were written with a goto in it, because it looks like a loop, but actually isn't one. With goto, at least it's very clear what it's for, even when there was a better way to do the same thing.
The code in question should of course be written with an if. A goto would not really be an improvement, both goto and break are really weird way to express something which seems to be simple conditional.
I agree goto's a fine if they are the simplest and most readable solution. But this does not seem to be such a case.
- Introduce scopes and program structure instead of explicit labels (instruction addresses) and using control flow operators which rely on this structure
- Procedures and procedure calls
- Overriding and virtual functions where the system knows how to find the next instruction to jump to
- Concurrency and multi-threading where resume operation means essentially jumping to some (dynamic, not static) instruction address.
- Asynchronous and even-driven programming
Gotos are not unavoidable in high level languages.
Is there any non-syntactic difference between these two lines?
JMP Ox1234
GOTO label_1234
I think they are identical and the question is only where target labels can reside, how they are represented, and when the jumps are triggered (operation).The code is, if not outright lying, at least misdirecting.
Second, experience has taught me that code and comments often don’t agree. Too, if you have to comment that a loop really isn’t a loop then this is an indication that something is wrong.
Third, it isn’t a loop: while(false) never loops. That’s the point. Having to use a forward reference to understand the beginning of something is bad practice.
Fourth, this construct is almost always a sloppy way to prevent if-else creep. The code is invariably improved by a) not lying about the loop and b) refactoring.
...
if (...) {
...
}
?Are there more complex examples where this becomes if-else hell?
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.");