【发布时间】:2014-04-06 11:08:49
【问题描述】:
我想使用 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;
}
}
多了一个变量,好像不是很好……
【问题讨论】:
-
如果这一切都是真的,那么很明显,列出所有可能性的全部目的是让您知道您无法存储返回值......所以您已经知道答案了。
-
伤心,这几乎毫无意义。我只想进行一般清理,并将 error_code 传递给另一个编译单元,当然不想 longjmp 到另一个编译单元。在我之前没有人遇到过这个问题??我做错了什么吗?