Alternatives to `while (1)` to simplify branching [duplicate]
Solution 1:
What other approach do you guys know/use?
You can encapsulate your while
loop in a function (and call this function where you had your while
loop):
static void process(void)
{
// process
if (!success) return;
// process
if (!success) return;
// process
if (!success) return;
// process
}
Any halfway decent compiler (e.g., even gcc
with optimizations disabled) will inline a static
function if it is called once. (Of course some variables may have to be in the lexical scope of process
function, in that case just provide them as parameters of the function).
Note that writing code from top to bottom instead of horizontally (e.g., your example with nested if
) is called duffing. There is a nice article on the subject here:
"Reading Code From Top to Bottom"
Also, in the Linux kernel coding style there is a specific warning writinh against horizontal code:
"if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program"
Solution 2:
The following is a method very similar to what you're doing with the loops, but without the need for a counter or a break
statement at the end.
do
{
// process
if (!success) break;
// process
if (!success) break;
// process
if (!success) break;
...
// No need for a break statement here
}
while(0);
Solution 3:
If you arrange that the body of each conditional block generating success
is a function as follows or each // process
can otherwise be reduced to a boolean expression, such as:
success = f1() ;
if( success )
{
success = f2() ;
if( success )
{
success = f3() ;
if( success )
{
success = f4()
}
}
}
Then you can reduce this to a single boolean expression exploiting short-circuit evaluation:
success = f1() &&
f2() &&
f3() &&
f4() ;
Here f2()
will not be called if f1()
returns false and the same for each successive call - expression evaluation aborts on the first &&
operand sub-expression to return false.