Is it good programming practice to use setjmp and longjmp in C?
There are some correct uses of setjmp/longjmp
. Implementing coroutines with them is virtually impossible, since you have to use (nonportable) tricks (read: inline assembly) to switch stacks.
One use of setjmp/longjmp
is to catch floating point signals, but this messes up the C++ stack unwinding. Correct in C though.
You can also implement some form of stack unwinding (by maintaining you own cleanup handler stack) and implement true destructors and exceptions in C with them. This is very handy in large projects: the lack of a correct error handling mechanism is the weak point of C. However, it is quite difficult to do it correctly, and you'll have to write a bunch of macros to facilitate the task.
they are used to implement coroutines. There are a couple of c++ coroutine libraries running around on the net, that in Unix/Linux will use setjmp/longjmp
to implement the functionality.
So, if your goal is to implement a coroutine library, then it is a moot point if its good practice or not, since on those platforms it is the only way to support that functionality.
if your goal is to use a coroutine library, you should search for some of these instead. There is even a boost vault proposal called boost::context, which is already approved.
Essentially, you're right in your assertion that jmp
-style propagation is essentially the same thing as goto
. Read Dijkstra's (famous and controversial) paper about goto
s which (I think) provides sensible reasoning for why goto
s should rarely be used. Unless you know exactly why you're doing what you're doing (or you're working in very specific fields -- such as embedded programming), you should not touch either goto
or longjmp
.