tags:

views:

964

answers:

12

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 gotos:

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.

+6  A: 

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!

AraK
+1 Use of GOTO is common in embedded systems to clean up after a failure.
g .
+1 Use of goto is not discouraged "just because". It's discouraged to avoid spaghetti code and to enhance clarity. The real rule is that the function should be clear and simple, so using an even harder to grasp alternative for goto isn't a good option IMO. Anything involving once-only loops would fall into this category.
Daniel Daranas
+2  A: 

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.

Aamir
+1  A: 

I think that this use (for resource management) of goto is ok.

dfa
A: 

I like the while(1) approach. I use it myself. Especially, when the loop might get repeated by continue, e.g. when an element is processed inside such loop, and it's done in multiple approaches.

A: 

Never use a condition loop with a permanently true condition. Since the condition is always true, why use a conditional loop?

Permanently true conditions are most directly represented by a goto.

Blank Xavier
I find while(1)+break+continue perfectly readable for me.. in opposition to goto, which is IMO unreadable.
@emg-2 I can read both. But "while(1)" communicates me a false idea of an infinite loop (which I have seen in other situations) and not a simple function which runs only once. "goto" is better for that purpose. All functions are either a sequence, a loop or a conditional.
Daniel Daranas
So you're saying that an application's message loop would be better represented with a goto to the beginning of the message handler instead of a while(1) or for(;;) ?
Tal Pressman
What he's saying is, the loop should have a terminating condition. Especially if -- as is the case here -- you are not intending to loop at all. With a message handling loop you do actually intend to leave it at some point, right? So why not build the terminating condition into the loop conditional?
jmtd
@emg-2: the readers ability to easily read or not easily read code does not relate to the semantic meaning of that code - here you are arguing for the use of semantically inappropriate code on the basis of readability - which is contradictory
Blank Xavier
@Tal: yes, absolutely. Would you use a goto with an if() inside which triggers a break, instead of using a while() with the condition?
Blank Xavier
@Tal: jtmd is correct - assuming no exit condition in the loop - if there is an exit condition, then (of course) you use a while().
Blank Xavier
+8  A: 

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.

Barry Kelly
The problem is not early exit, it is cleanup. In a multistep init, you eventually need to cleanup / deallocate what was already successfully allocated.
shodanex
This is what I was going to suggest. Failing that, I would use goto over while(1), because while(1) gives the misleading impression that the code loops, when in fact it doesn't.
MrZebra
@shodanex: it might just be the case that the language is not expressive enough to natively express what you wanted to do (that is, a "finally" clause like in java). so any kind of hacks to get around that limitation is going to have some cons associated with it.
Chii
A method call may have performance impacts caused by increasing the stack as well as possible stack overflow exceptions. This is one of the reasons you see them in drivers and kernel code.
Matthew Whited
A: 

While using "goto" for error handling situations is fairly common, I'd still prefer the "while" solution (or "do while"). In the "goto" case, there are far fewer things that the compiler can guarantee. If you make a typo in the label name, the compiler can't help you there. If someone uses another goto to another label in that block, there's a good chance the cleanup code won't get called. When you use the more structured flow control constructs you are always guaranteed which code will run once the loop is over.

Tal Pressman
The compiler can catch label typos easily: temp.c:9: error: label ‘blarg4h’ used but not defined temp.c:7: warning: label ‘blargh’ defined but not used
jmtd
+7  A: 
Makis
Awful, yet clear.
Arafangion
if `do_something1()` returns `1` then 2nd line changes `error` to `0` again and `do_something3()` is executed. It might be not what you want.
J.F. Sebastian
+1  A: 

Use it if you can't use goto for whatever reason

  • forbidden in your project's conventions
  • forbidden by your lint tool

I also think that is also one of the cases where macros aren't evil:

#define DO_ONCE for (int _once_dummy = 0; _once_dummy < 1; _once_dummy++)
yairchu
In C89, declaring a variable in a loop is not allowed. It is permitted in C99.
jmtd
+16  A: 

The seemingly universal revultion to GOTO is largely due to Edsger Dijkstra's letter "Go To Statement Considered Harmful".

If you are determined not to use goto, something like

do {
    ...
while(0);

is probably safer than while(1) { ... } since it guarantees that you will not inadvertently loop (and if you are inadvertently looping, with while(1) you are probably inadvertently looping infinitely).

The one advantage that (ab)using do/break/while or while/break for this purpose has over goto is that you are guaranteed not to be jumping above the construct -- goto can be used to jump to a label earlier within the same function.

The disadvantage that do/break/while etc. have over goto is that you are limited to one exit point (immediately after the loop). In some cases you might need a staged cleanup: e.g., when you open a file handle, malloc some memory, read from the file... if the read fails, you need to clean up the malloc. If the malloc fails, you don't need to clean it up, but you still need to clean up the file handle. With goto, you can have one label per stage of cleanup and jump to precisely the right point depending on where your error occurred.

In my opinion blindly avoiding GOTO because of the prevalent hatred of it is more damaging than carefully reasoning out a case for its use on a case-by-case basis. A rule of thumb I use is "does the Linux kernel do it? If so, it can't be that bad". Substitute linux kernel with any other good example of modern software engineering.

jmtd
+1 Haven't noticed your answer somehow :-)
liori
Actually it's not only Linux kernel, Windows Drivers samples from MS full of goto's, Solaris unix kernel drivers use it as well, BSD kernel code, etc ... The bottom line goto is used and used widely mostly by people knowing what they are doing.
Ilya
I've seen code using the `do { ... break ... } while(0);` trick, and I can attest that it hampers readability while not buying you anything. If you're doing a `goto` - and you _are_ doing it here anyway - then at least be explicit about it.And there's nothing wrong about `goto` in C code for error handling / cleanup purposes.
Pavel Minaev
+2  A: 

Why not use a series of if statements? I usually write it this way, as I find it much clearer than a loop:

bool ok = true;

do_something();
if (was_an_error()) ok = false;

if (ok)
{
    do_something_else();
    if (was_an_error()) ok = false;
}

if (ok)
{
    do_something_else_again();
    if (was_an_error()) ok = false;
}

[...]

[Cleanup code]

Also if you are working to strict coding standards, yes goto is likely to be forbidden, but often so are break and continue so the loop is not necessarily a workaround for that.

finnw
That can be compressed a little: if(ok) {do_something(); ok = was_an_error();}
Steve Melnikoff
@Steve don't you mean ok = ! was_an_error() ?
finnw
In a real-time system this could have a performance penalty. You are doing several conditional jumps instead of just one.
Matthew Whited
@Matthew, an optimising compiler can spot that if one `if (ok)` test fails, then so will all the remaining tests, so it can jump directly to the exit point.
finnw
A: 

"break" understands the semantics of the block scope, while "goto" is oblivious to it. In other words, "while-break" can be translated into functional languages like Lisp with tail-recursion, "goto" cannot.

yogman