0

I am tinkering with setjmp and longjmp, implementing a simple try/catch exception system with them. setjmp will return the integer 0 upon first calling it, and returns any other value you pass in into the call to longjump otherwise.

However, according to this resource, which I presume is based on the C99 standard it actually is not allowed (in strict C99) to read out the result of setjmp and store it in a variable.

Because of this, as well as because we might want to pass data that is different (e.g. larger than) an integer between longjmp and setjmp, I am looking to alternatives to pass data (an integer or a (pointer to a) struct) back up.

How can we do that (while keeping standads-compliant, i.e. not threading in 'undefined behaviour' territory)?

Qqwy
  • 5,214
  • 5
  • 42
  • 83
  • Using setjmp/longjmp is 10x worse evil than using goto. I doubt anyone, including you, will be able to debug such code few months later. – mvp May 04 '18 at 17:59
  • 2
    Before the setjmp, allocate/define some structure to hold whatever data you want. Write the data before the longjmp, read it after. – Eric Postpischil May 04 '18 at 19:05
  • @mvp Using goto is not evil, but it is considered harmful (to readability/maintainability) iff you use it where you could have used higher-level built-in flow control constructs. Dijkstra's argument is not 'never use goto' but 'only use goto when you have to'. There is no other way than setjmp/longjmp to perform nonlocal returns in C. By wrapping these inside their own library of constructs, we separate the concerns of library code (written to be concise as to remain debuggable) and an outward interface that follows the principle of least surprise,making user(library consumer) code debuggable. – Qqwy May 05 '18 at 05:08

0 Answers0