RAD Studio
ContentsIndex
PreviousUpNext
setjmp

Header File 

setjmp.h  

Category 

Miscellaneous Routines 

Prototype 

int setjmp(jmp_buf jmpb); 

Description 

Sets up for nonlocal goto. 

setjmp captures the complete task state in jmpb and returns 0. 

A later call to longjmp with jmpb restores the captured task state and returns in such a way that setjmp appears to have returned with the value val. 

Under Win32, a task state includes:

  • No segment registers are saved
  • Register variables
  • EBX, EDI, ESI
  • Stack pointer (ESP)
  • Frame pointer (EBP)
  • Flags are not saved
A task state is complete enough that setjmp can be used to implement co-routines. 

setjmp must be called before longjmp. The routine that calls setjmp and sets up jmpb must still be active and cannot have returned before the longjmp is called. If it has returned, the results are unpredictable. 

setjmp is useful for dealing with errors and exceptions encountered in a low-level subroutine of a program. 

Return Value 

setjmp returns 0 when it is initially called. If the return is from a call to longjmp, setjmp returns a nonzero value (as in the example). 

Example  

#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
void subroutine(jmp_buf);
int main(void)
{
    
    int value;
    jmp_buf jumper;
    value = setjmp(jumper);
    if (value != 0) 
    {
       printf("Longjmp with value %d\n", value);
       exit(value);
    }
    printf("About to call subroutine ... \n");
    subroutine(jumper);
    return 0;
}
void subroutine(jmp_buf jumper)
{
    longjmp(jumper,1);
}

Portability

POSIX 
Win32 
ANSI C 
ANSI C++ 
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!