Previous Page
Next Page

16.13. Nonlocal Jumps

The goto statement in C can be used to jump only within a function. For greater freedom, the header setjmp.h declares a pair of functions that permit jumps to any point in a program. Table 16-27 lists these functions.

Table 16-27. Nonlocal jump functions

Purpose

Function

Save the current execution context as a jump target for the longjmp( ) function

setjmp( )

Jump to a program context saved by a call to the setjmp( ) function

longjmp( )


When you call the function-like macro setjmp( ), it stores a value in its argument with the type jmp_buf that acts as a bookmark to that point in the program. The jmp_buf object holds all the necessary parts of the current execution state (including registers and stack). When you pass a jmp_buf object to longjmp( ), longjmp( ) restores the saved state, and the program continues at the point following the earlier setjmp( ) call. The longjmp( ) call must not occur after the function that called setjmp( ) returns. Furthermore, if any variables with automatic storage duration in the function that called setjmp( ) were modified after the setjmp( ) call (and were not declared as volatile), then their values after the longjmp( ) call are indeterminate.

The return value of setjmp( ) indicates whether the program has reached that point after the original setjmp( ) call, or through a longjmp( ) call: setjmp( ) itself returns 0. If setjmp( ) appears to return any other value, then that point in the program was reached by calling longjmp( ). If the second argument in the longjmp( ) callthat is, the requested return valueis 0, it is replaced with 1 as the apparent return value after the corresponding setjmp( ) call.


Previous Page
Next Page