C庫宏 - setjmp()



C庫宏setjmp() 將當前的環境儲存到變數environment中,以便稍後由函式longjmp()使用。如果該宏直接從宏呼叫返回,則返回零;如果它從longjmp()函式呼叫返回,則返回傳遞給longjmp作為第二個引數的值。

此函式用於在C中實現異常處理。

語法

以下是C庫宏setjmp()的語法:

setjmp(jmp_buf environment)

引數

此函式只接受一個引數:

  • environment - 這是jmp_buf型別的物件,其中儲存環境資訊。

返回值

此宏可能多次返回。第一次,在其直接呼叫時,它總是返回零。當longjmp使用設定為environment的資訊呼叫時,宏再次返回;現在它返回傳遞給longjmp作為第二個引數的值。

示例1

以下是一個基本的C程式,它顯示了setjmp()函式的使用方法。

#include <setjmp.h>
#include <stdio.h> 
jmp_buf buf; 
void func() 
{ 
   printf("Welcome to Tutorialspoint\n"); 

   // Jump to the point setup by setjmp 
   longjmp(buf, 1); 

   printf("Python Tutorial\n"); 
} 

int main() 
{ 
   // Setup jump position using buf and return 0 
   if (setjmp(buf))
   printf("Java Tutorial\n"); 
   else { 
   printf("The else-statement printed\n"); 
   func(); 
	} 
   return 0; 
}

輸出

以上程式碼產生以下結果:

The else-statement printed
Welcome to Tutorialspoint
Java Tutorial

示例2

在這個例子中,我們演示了函式longjmp()和setjmp()的標準呼叫和返回序列。

#include <stdio.h>
#include <setjmp.h>
#include <stdnoreturn.h>
 
jmp_buf my_jump_buffer;
 
noreturn void foo(int status) 
{
   printf("foo(%d) called\n", status);
   longjmp(my_jump_buffer, status + 1); 
}
 
int main(void)
{
   volatile int count = 0; 
   if (setjmp(my_jump_buffer) != 5) 
       foo(++count);
   return 0;
}

輸出

執行上述程式碼後,我們得到以下結果:

foo(1) called
foo(2) called
foo(3) called
foo(4) called

示例3

以下是setjmp()函式的另一個示例。

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

int a(char *s, jmp_buf env) {
   int i;

   i = setjmp(env);
   printf("Setjmp returned %d\n", i); 
   printf("S = %s\n", s);
   return i;
}

int b(int i, jmp_buf env) {
   printf("In b: i = %d, Calling longjmp\n", i);
   longjmp(env, i);
}

int main() {
   jmp_buf env;

   if (a("Tutorial", env) != 0)
       exit(0); 
   b(3, env);
   return 0;
}

輸出

執行上述程式碼後,我們得到以下結果:

Setjmp returned 0
S = Tutorial
In b: i = 3, Calling longjmp
Setjmp returned 3
S = ��UH��H���
廣告
© . All rights reserved.