setjmp, longjmp

#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>

static void f1(int, int, int);
static void f2(void);

static jmp_buf jmpbuffer;

int main(int argc, char *argv[])
{
    int count; /*the value is on stack, it will be changed after longjmp*/
    register int val;	/*the value is in register, it will be changed after longjmp*/
    volatile int sum;	/*the value won't be changed after longjmp, because it is read from the memory, instead of the register*/

    count = 2; 
    val = 3;
    sum = 4;

    if(setjmp(jmpbuffer) != 0)
    {
        printf("after longjmp: count = %d, value = %d, sum = %d\n", count, val, sum);
	exit(0);
    }
    count = 97; val = 98; sum = 99;
    f1(count, val, sum);

    return 0;
}

static void f1(int i, int j, int k)
{
    printf("in f1(): count = %d, val = %d, sum = %d\n", i, j ,k);
    f2();
}

static void f2(void)
{
    /*stack and registers will be destroyed, and values stored on them are uncertain*/
    longjmp(jmpbuffer, 1);
}

你可能感兴趣的:(long)