Practical usage of setjmp and longjmp in C

前端 未结 8 1778
忘了有多久
忘了有多久 2020-11-28 01:48

Can anyone explain me where exactly setjmp() and longjmp() functions can be used practically in embedded programming? I know that these are for err

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 02:23

    The theory is that you can use them for error handling so that you can jump out of deeply nested call chain without needing to deal with handling errors in every function in the chain.

    Like every clever theory this falls apart when meeting reality. Your intermediate functions will allocate memory, grab locks, open files and do all kinds of different things that require cleanup. So in practice setjmp/longjmp are usually a bad idea except in very limited circumstances where you have total control over your environment (some embedded platforms).

    In my experience in most cases whenever you think that using setjmp/longjmp would work, your program is clear and simple enough that every intermediate function call in the call chain can do error handling, or it's so messy and impossible to fix that you should do exit when you encounter the error.

提交回复
热议问题