#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static jmp_buf buf1, buf2;
int cnt1 = 0, cnt2 = 0;
int main(int argc, char **argv)
{
printf("Starting\n");
// Setjmp will save the registers in buf1 when called (which is only
// once) and return 0, but will return again each time longjmp is
// called with buf1, returning a non-zero value. Called once, returns
// many times.
if(setjmp(buf1)) {
// Just print the counter
int i;
for(i = 1; i <= 3; ++i)
printf("A %d\n", cnt1++);
if(cnt2 > 5) exit(1);
// Copy the contents of buf2 into the physical registers,
// which changes the PC to what it was when they were recorded,
// transferring control to the setjmp(buf2).
longjmp(buf2, 2);
}
printf("Middle\n");
int i;
for(i = 1; i <= 3; ++i)
printf("M %d\n", cnt1++);
// This will set the registers into buf2, also returning zero the
// first time (real return), and nonzero the many additional times
// it returns.
int ret = setjmp(buf2);
printf("Setjmp returns %d\n", ret);
for(i = 1; i <= 2; ++i)
printf("B %d\n", cnt2++);
// As above, restore the register state saved in buf1 to the physical
// registers, causing return from but buf1 setting.
longjmp(buf1, 1);
printf("Never prints\n");
}