Table of Contents

setjmp

int setjmp ( jmp_buf env );

description of setjmp

save program state / environment to the stack for a longjump useful for debugging.

#include <stdio.h>
#include <setjmp.h>
 
void testit(int);
jmp_buf program_state;
 
static int count;
void testit(int count) {
 
   count++; // set counter +1 but it will never reach 2
   printf("count is now %i\n", count);
   }
 
int main(void) {
   count = 0;
   printf("count starts with: %i\n", count);
 
   if(setjmp(program_state) == 0) {
       printf("save program state in the stack\n");
       testit(count);
   }
   else {
        printf("callback with longjmp\n");
        testit(count);
        testit(count);
        return 0;
   }
 
   testit(count);
   longjmp(program_state,1);
   printf("never called\n");
   testit(count);
 
   return 0;
}

output of setjmp c example

  count starts with: 0
  save program state in the stack
  count is now 1
  count is now 1
  callback with longjmp
  count is now 1
  count is now 1