c - How to safely get the return value of setjmp -
i return error code using longjmp, , pass on function called setjmp. simplified code:
int do_things(stuff ........) { int error_code; jmp_buf jb; if ((error_code = setjmp(jb)) == 0) { /* stuff */ return 0; } else { return error_code; } }
but i'v read: "an invocation of setjmp macro shall appear in 1 of following contexts:"
entire controlling expression of selection or iteration statement if (setjmp(jb)) { switch (setjmp(jb)) { while (setjmp(jb)) {
or
1 operand of relational or equality operator other operand integer constant expression, resulting expression being entire controlling expression of selection or iteration statement if (setjmp(jb) < 3) {
or
operand of unary ! operator resulting expression being entire controlling expression of selection or iteration statement if (!setjmp(jb)) {
or
entire expression of expression statement (possibly cast void). setjmp(bf);
is there nice way return value? ( without using switch
, , writing case
possibly values )
edit
thanks matt finding in c99 rationale. came now, is:
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; } }
one more variable, doesn't seem nice...
from c99 rationale:
one proposed requirement on setjmp usable other function, is, callable in expression context, , expression evaluate correctly whether return setjmp direct or via call longjmp. unfortunately, implementation of setjmp conventional called function cannot know enough calling environment save temporary registers or dynamic stack locations used part way through expression evaluation. (a setjmp macro seems if expands inline assembly code or call special built-in function.) temporaries may correct on initial call setjmp, not on return initiated corresponding call longjmp. these considerations dictated constraint setjmp called within simple expressions, ones not need temporary storage.
an alternative proposal considered c89 committee require implementations recognize calling setjmp special case, , hence take whatever precautions necessary restore setjmp environment upon longjmp call. proposal rejected on grounds of consistency: implementations allowed implement library functions specially, no other situations require special treatment.
my interpretation of considered restrictive specify a = setjmp(jb);
must work. standard leaves undefined. particular compiler may choose support (and hopefully, document it). portable, guess should use preprocessor checks verify code being compiled compiler known support this.
Comments
Post a Comment