4 ms·
A bit of a tangent, there are few instances of "do-while" that I've ever ever written and not removed soon after. In practice, I've found that the looping situa
by jstimpfle 4y ago
A bit of a tangent, there are few instances of "do-while" that I've ever ever written and not removed soon after. In practice, I've found that the looping situations that don't easily match the "for (int i = 0; i < n; i++)" pattern are normally "random" enough that it's best to just write "for (;;)" and put explicit checks and breaks inside the body, wherever they naturally fit. Forcing "for (...)" or "while (...)" or "do-while(...)" syntactic constructs is likely to lead to an unnatural sequence of statements. Doing break anywhere is just fine!
do
{
splice(from stdin...);
if (A)
handle_a();
goto out;
splice(to stdout...);
if (B)
handle_b();
goto out;
} while (nwritten > 0);
// do we need some kind of handle_c()??
out:
...
Why make a special case for the "nwritten > 0" condition here? And what's wrong with "break" vs "goto"?
for (;;)
{
thing_a();
if (A)
handle_a();
break;
thing_b();
if (B)
handle_b();
break;
if (C)
handle_c();
break;
}
is cleaner in my eyes.
- faho 4y agoFirst of all: Your code is missing braces around the `if` blocks - the `goto out` would be run unconditionally. But anyway, the case for `goto` here is that it jumps immediately to the cleanup that needs to happen always. If you put something between the loop and that, `break` would jump before that and also execute that. Yes, this is a workaround for C's lack of automatic cleanup (RAII, garbage collection, python's `with` or whatever).
- jstimpfle 4y ago> Your code is missing braces around the `if` blocks Sure. It's obviously a sketch. > If you put something between the loop and that, `break` would jump before that and also execute that. Sure. But I rarely can see a need to make it so complicated (not in this case anyway). If you need multiple distinct cleanup sections that can't be inlined, then label them all (or put them in separate procedures) and jump to them explicitly. In my example, there is no need for any labels at all. > this is a workaround for C's lack of automatic cleanup (RAII, garbage collection, python's `with` or whatever). No need for workarounds here.
- sharikous 4y ago"do ... while" maps neatly into Assembly for me. I think it is meant as a bridge between low level thinking and structured programming.