Linux環境編程之進程(三):函數間跳轉

來源:互聯網
上載者:User

標籤:setjmp   longjmp   函數間跳轉   

引言:在編寫程式時,經常在函數內部使用goto語句來跳轉,從而進行出錯處理,那麼如果想要在函數之間進行跳轉該怎麼做呢?使用setjmp和longjmp函數。

給出樣本程式:

#include <stdio.h>#include <stdlib.h>#include <setjmp.h>static void f1(int, int, int, int);static void f2(void);static jmp_buf jmpbuffer;static int globval;intmain(void){int autoval;register int regival;volatile int volaval;static int  statval;globval = 1;autoval = 2;regival = 3; volaval = 4;statval = 5;if(setjmp(jmpbuffer) != 0){printf("after longjmp:\n");printf("global = %d, autoval = %d, regival  = %d, volaval = %d, statval = %d\n", globval, autoval, regival, volaval, statval);exit(0);}/* * Change variable after setjmp, buf before longjmp. */globval = 95;autoval = 96;regival = 97; volaval = 98;statval = 99;f1(autoval, regival, volaval, statval);/*never returns*/exit(0);}static voidf1(int i, int j, int k, int l){printf("in f1():\n");printf("global = %d, autoval = %d, regival  = %d, volaval = %d, statval = %d\n", globval,i, j, k, l);f2();}static voidf2(void){longjmp(jmpbuffer, 1);}

編譯器測試結果:

in f1():global = 95, autoval = 96, regival  = 97, volaval = 98, statval = 99after longjmp:global = 95, autoval = 96, regival  = 97, volaval = 98, statval = 99


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.