Section 16.13. Nonlocal Jumps


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.



C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net