5 ms·
On the topic of loops which end in a break ("Most egregious is the loop whose last statement is break;!"): this can be useful for avoiding contorted control flo
by barrkel 15y ago
On the topic of loops which end in a break ("Most egregious is the loop whose last statement is break;!"): this can be useful for avoiding contorted control flow when you have a switch statement inside the loop. Instead of coding:
cont = 1;
while (cont)
{
foo = bar();
switch (foo)
{
case 0:
cont = 0;
break;
default:
// other work
break;
}
}
You can do this instead:
for (;;)
{
foo = bar();
switch (foo)
{
case 0:
break;
default:
// other work
continue;
}
break;
}
IMO the idiom, once you're used to it, reads better.
(Yes, I know you can reduce the lines further e.g. putting foo=bar() into the for statement, but it's the multi-level break I'm focused on here.)
- ch 15y agoWhy not: while( (foo = bar()) != 0 ) { /* other work */ } Or even simpler (since 'foo' serves no real purpose in the example): while( bar() ) { /* other work */ }
- deleted 15y ago[deleted]