I found the following code in a C program:
while (1)
{
do_something();
if (was_an_error()) break;
do_something_else();
if (was_an_error()) break;
[...]
break;
}
[cleanup code]
Here while(1)
is used as local emulation of "finally". You can also write this using goto
s:
do_something()
if (was_an_error()) goto out;
do_something_else()
if (was_an_error()) goto out;
[...]
out:
[cleanup code]
I thought the goto solution is a usual idiom. I have seen several occurrences of this idiom in the kernel sources and it is also mentioned in Diomidis Spinellis' "Code Reading" book.
My question is: What solution is better? Is there any specific reason to use the while(1)
solution?
Question 943826 doesn't answer my question.
I know my style isn't the coolest possible, but I prefer it because it doesn't need any special constructs and is concise and not too hard to understand:
Normally, GOTOs are considered bad but at some places where there are only Forward Jumps through GOTOs, they are not AS bad. People avoid GOTO like plague but a well-thought-out use of GOTO is sometimes a better solution IMHO.
Though the use of goto is discouraged usually, some rare situations like yours is a place where best-practices are not the best.
So, if goto makes the clearest code I would use it. using a while(true) loop to emulate goto is something unnatural. What you really need is a goto!
"do while" and "goto out" are different on these area:
1.local variable initialization
It is fine to initialize in-place local variables in do ... while(0) block.
2 difference for Macros. "do while" is a slight better. "goto DONE" in a Macro is so not the case. If the exit code is more complicated, let see like this:
and you write this code again and again, you will probably put them into a Macro.
And the code become:
3.do... while(0) handles different levels of exiting with same macro. Code is shown above. goto ... is not the case for Macro cause you need different labels for different levels.
By saying that, I do not like both of them. I'd prefer to use the exception method. If exception is not allowed, then I use "do ... while(0)", since the whole block is indented, it is actually easier to read than "goto DONE" style.
Putting the code into a separate function, and using
return
to exit early is another way to do it, with the benefit of easy integration of a return code indicating the nature of the failure.Why not use a series of
if
statements? I usually write it this way, as I find it much clearer than a loop:Also if you are working to strict coding standards, yes
goto
is likely to be forbidden, but often so arebreak
andcontinue
so the loop is not necessarily a workaround for that.