From: Warner Losh
In C I use it all the time to do goto err for common
error recovery
because C doesn't have anything better.
That's because C doesn't have 'conditions'. (Apparently, from the
following
posts, most people here are unfamiliar with them. Too bad, they are a great
idea. OK summary here:
http://gunkies.org/wiki/Condition_handler
for those who are unfamiliar with the idea.)
I was at one point writing a compiler using a recursive descent parser, and
decided the code would be a lot simpler/cleaner if I had them. (If, for
example, one discovers discovers an un-expected 'end of file', there can be
an extremely large number of procedure invocations in between where that is
discovered, and where it is desirable to handle it. So every possible
intervening procedure would have to have an 'unexpected EOF' return value,
one would have to write code in every possible intervening procedure to
_handle_ an 'unexpected EOF' return value, etc.)'
(Yes, I could have used setjmp/longjmp; those are effectively a limited
version of condition handlers.)
Since C has a stack, it was relatively easy to implement, without any compiler
support: on() became a macro for 'if _on("condition_name")'; _on() was
a
partially-assembler procedure which i) stacked the handler (I forget where I
put it; I may have created a special 'condition stack', to avoid too many
changes to the main C stack), and ii) patched the calling procedure's return
point to jump to some code that unstacked the handler, and iii) returned
'false'. If the condition occurred, a return from _on() was simulated,
returning 'true', etc.
So the code had things like:
on ("unexpected EOF") {
code to deal with it
}
With no compiler support, it added a tiny bit of overhead
(stacking/unstacking conditions), but not too bad.
John Wroclawski and someone implemented a very similar thing
entirely in C; IIRC it was built on top of setjmp/longjmp. I don't
recall how it dealt with un-stacking handlers on exit (which mine
did silently).
Noel