setjmp() and longjmp()

簡單地瞭解了一下setjmp()和longjmp(),它們的功能大抵就是實現一個跳轉。

setjmp(jmp_buf) 需要一個jmp_buf的變量來儲存當前數據,longjmp(jm_buf, int) 需要兩個參數,一個是setjmp用的jmp_buf,另一個是int。當調用longjmp()是,程序流程跳轉到對應setjmp的位置執行,並把longjmp()中參數int的值作爲setjmp()的返回值,程序繼續執行。

我寫了一個小程序,通過這個小程序,很容易看出這兩個函數是什麼關係。

/*
 * setjmp() and longjmp()
 * mike-w
 * 2012-9-30
 * *************************************
 * 有人用setjump()/longjump()
 * 可在我這隻能用setjmp()/longjmp()
 * 不知道什麼原因 :-(
 * environment: gcc 4.5.2 on win7
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<setjmp.h>

jmp_buf buf1;

int foo(void)
{
	int op;
	puts("now you are in foo()");
	puts("select a sentence below:");
	puts("1. have a nice day");
	puts("2. nice to meet you");
	puts("3. it's raining cats and dogs");
	while(scanf("%d", &op)!=1 || op<=0 || op>3)
		fflush(stdin);
	puts("jumping from foo() to main()...");
	longjmp(buf1, op);
	return 0;
}

int main(void)
{
	puts("now you are in main()");
	switch(setjmp(buf1))
	{
		case 0:
			puts("you are still in main()");
			puts("calling foo()...");
			foo();
			break;
		case 1:
			puts("have a nice day");
			break;
		case 2:
			puts("nice to meet you.");
			break;
		case 3:
			puts("it's raining cats and dogs");
			break;
		default:
			puts("error!");
	}
	return 0;
}

執行結果:

now you are in main()
you are still in main()
calling foo()...
now you are in foo()
select a sentence below:
1. have a nice day
2. nice to meet you
3. it's raining cats and dogs
2 <- 這是我的輸入
jumping from foo() to main()...
nice to meet you.


發佈了204 篇原創文章 · 獲贊 4 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章