liveBook · Manning

Setjmp/longjmp

As explained in Modern C, Third Edition

A long jump is a nonlocal control transfer that can move execution across function-call boundaries.

An output failure during recursive descent

A recursive parser checks whether writing a newline failed. If `putchar('\n') == EOF`, it calls `longjmp(jmpTarget, eofOut)` instead of returning through each active call. Its outer function uses `switch (setjmp(jmpTarget))` to select an outcome, including an output-error message. section 19.5

`setjmp` establishes a target in a `jmp_buf`; `longjmp` transfers control back to that target across function-call boundaries. Unlike a `goto` label, the target need not be in the same function. `setjmp` may return more than once, while `longjmp` never returns to its caller. section 19.5 section 19.0

TAKEAWAY — keep the recovery path valid and portable:

  • Use a `jmp_buf` only while it is alive and its contents are valid. section 19.5
  • Place the `setjmp` macro only in expression contexts permitted by the C standard; an implementation might not diagnose an invalid placement. section 15.3.3
  • Account for optimization when a long jump crosses active calls: some variables require `volatile` qualification. section 19.7
Figure 19.2 Control flow with setjmp and longjmp: longjmp jumps to the position marked by setjmp.
figure

The control-flow figure shows the jump from `longjmp` back to the position marked by `setjmp`. section 19.5

How Modern C, Third Edition covers it

How deep it goes
Works through a recursive parser and states target-validity, macro-placement, and volatile constraints without detailing jump-buffer internals.
Examples
Uses a recursive parser whose output failure triggers `longjmp` and whose outer `switch` handles the resulting condition.
What it assumes
Assumes familiarity with function calls, recursion, and `switch`, while introducing `jmp_buf` as the jump target.
What you can do after
Apply it via C’s `<setjmp.h>` interface to route exceptional nested-call failures to a valid recovery target.
How it connects
Connects nonlocal control flow to recursive descent, goto, basic blocks, and compiler optimization.

Also explained in

Compare how 3 books explain setjmp/longjmp →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.