3 ms·
> In C you can certainly jump "sideways". The condition for using longjmp is that the function where the context had been saved has not terminated. This means a
by JoshTriplett 11y ago
> In C you can certainly jump "sideways". The condition for using longjmp is that the function where the context had been saved has not terminated. This means a function can longjmp to itself (regardless of block nesting).
However, you can't longjmp to a function that's a "sibling" in the call tree: if f() calls a(), then calls b(), b can't longjmp to a, though it can longjmp to f.
- kazinator 11y agoThat's covered by "can't call down". f() can't jump back into a() after a() returns, and that restriction isn't going to go away if b() is called. (If anything, the actual behavior is worse because b() will blindly execute over the a() stack frame, whereas if f() calls a(), it's actually possible (though not ISO-C-defined), and the basis of some historic coroutine hacks.)
- JoshTriplett 11y agoIt's not unreasonable to think of it as "sideways", though. Because the only other interesting meaning of "sideways" is "into another part of the same function", and that's covered by a simple goto, without even using setjmp/longjmp.
- kazinator 11y agoIt's covered by the GNU C computed goto, maybe, not the static ISO C goto. longjmp is a computed goto; it goes wherever the jmp_buf's run-time contents indicate. This is not only academic; this use case occurs in exception handling based on setjmp/longjmp, when a "finally" type cleanup block catches an exception, and the throw originates from the same function (the "finally" block's corresponding "try").