From time to time, I use a while(1)
block to flatten a succession of if..else
going out of proportion. It goes along these lines.
Instead of doing:
// process
if (success) {
// process
if (success) {
//process
if (success) {
// etc
}
}
}
I do:
while (1) {
// process
if (!success) break;
// process
if (!success) break;
// process
if (!success) break;
// etc
break;
}
I am a little annoyed by the implicit jump at the end of the while
. Could I get away with a leaner construct (ie no break
at the end)?
I could trade the final break
with a variable (or register?). That's not exactly leaner or clearer.
int once = 1;
while (once--) {
// process
if (!success) break;
// process
if (!success) break;
// process
if (!success) break;
// etc
}
A for loop would look a bit better (C99):
for (int once = 1 ; once--; once) {
// process
if (!success) break;
// process
if (!success) break;
// process
if (!success) break;
// etc
}
I thought about using a switch case. It does not look much better , though it would work.
switch (1) { default:
// process
if (!success) break;
// process
if (!success) break;
// process
if (!success) break;
// etc
}
In that particular case the concept of a label seems unbeatable.
// process
if (!success) goto end;
// process
if (!success) goto end;
// process
if (!success) goto end;
// etc
end:
What other approach do you guys know/use?