top | item 13056978

(no title)

yekim | 9 years ago

Yes - a thousand times yes!

The goto has gotten a bad rap over the years because of Dijkstra's paper. And that paper has unduly influenced a lot of incorrect thinking. There are valid use cases for goto, and this is certainly one of them.

I use it all the time like the example above. Particularly because it makes my life so much easier when developing and debugging embedded C code across various tool chains, some of which have less functionality than others.

[edit - correct typo on Ed's name]

discuss

order

Watabou|9 years ago

Just curious, not a C developer by any means, but why wouldn't you use a function here instead of a goto? I'm confused how goto would reduce error/improve readability in that example.

Again, not criticizing, genuinely want to know.

emptybits|9 years ago

Simply: a goto never returns while a function call returns to where it was called from.

So specifically in the example above, if you called failure-handling functions instead of using goto's then when the function returned you would continue execution on the next line after the function call. In the example above, that's clearly not what you want.

Now you could add some else's after the function calls to prevent execution from continuing. i.e. to get to the appropriate step in the free_* sequence at the bottom, but that starts to look messy. So I have to admit (not being a goto-lover), the above example reads very nicely.

It conforms to the "gotos might be okay if they only jump forward" rule of thumb I've heard.