Search code examples
cexceptionunix

Is it good programming practice to use setjmp and longjmp in C?


I'm a C++ programmer and used to OO languages with good exception handling.

From what I can understand, setjmp and longjmp are essentially a c-style way to propogate exception conditions. They also seem like an intense form of goto that can propogate up the stack.

So, first of all: Is it good practice to use these in straight up C as of this point in time, or are they deprecated? (note: C not C++).

Secondly, do they have any use in C++ or am I correct in thinking they were a legacy mechanism which was replaced by exception handling features of C++?


Solution

  • 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 gotos which (I think) provides sensible reasoning for why gotos 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.