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

前端 未结 8 1872
误落风尘
误落风尘 2021-02-07 10:28

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 ex

8条回答
  •  时光说笑
    2021-02-07 11:19

    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.

提交回复
热议问题