我想使用 longjmp 返回一个错误代码,并从调用 setjmp 的函数传递它。简化代码:
int do_things(stuff ........)
{
int error_code;
jmp_buf jb;
if ((error_code = setjmp(jb)) == 0) {
/* do stuff */
return 0;
}
else {
return error_code;
}
}
但我读过:“setjmp 宏的调用应仅出现在以下上下文之一中:”
the entire controlling expression of a selection or iteration statement
if (setjmp(jb)) {
switch (setjmp(jb)) {
while (setjmp(jb)) {
或者
one operand of a relational or equality operator with the other operand
an integer constant expression, with the resulting expression being
the entire controlling expression of a selection or iteration statement
if (setjmp(jb) < 3) {
或者
the operand of a unary ! operator with the resulting
expression being the entire controlling expression of a
selection or iteration statement
if (!setjmp(jb)) {
或者
the entire expression of an expression statement (possibly cast to void).
setjmp(bf);
有没有很好的方法来获取返回值?(不使用,并为所有可能的值switch
写一个)case
编辑
感谢 Matt 在 c99 基本原理中找到它。我现在想出的是:
int do_things(stuff ........)
{
volatile error_code;
jmp_buf jb;
if (setjmp(jb) == 0) {
working_some(&error_code, ....);
working_again(&error_code, ....);
working_more(&error_code, ....);
working_for_fun(&error_code, ....);
return 0;
}
else {
general_cleanup();
return error_code;
}
}
多了一个变数,好像不太好看……