|
|
|
|
|
by kator
4258 days ago
|
|
I always cringe when I see or have to write: for ( ; ; )
or: while ( true )
etc.You just know you're setting yourself up for undocumented bugs later. I've been known to build "escape" vars into these like: int attempts = 1000;
for(;attempts > 0;attempts--) {
** DO SOMETHING **
}
if (attempts <= 0) {
** BAIL ***
}
Where 1000 or whatever number is a reasonable estimate of the function's need to loop x 10 or etc. |
|
1. Some initialization (optional). 2. Some stuff you do each iteration (optional). 3. Check the exit condition and exit the loop (optional). 4. Some stuff you do each iteration (optional).
"while" loops nicely handle the case where 2 is empty. "do while" loops handle 4 being empty. "for" loops handle both 2 and 4 being non-empty but only really accommodate 4 being a single expression.
For any other case where 2 is non-empty and 4 is more than a single expression, I just use a "while (true)" with an "if (...) break;" in the body.