longjmp - How does Non - local Jumps in C defined in setjmp.h work? -


the c reference manual, appendix b describes 2 functions setjmp , longjmp called non-local jumps. apart basic understanding setjmp saves state information , longjmp restores state, haven't been able understand exact flow , use cases feature.

so, feature accomplish , useful?

as control flow: setjmp returns twice, , longjmp never returns. when call setjmp first time, store environment, returns zero, , when call longjmp, control flow passes return setjmp value provided in argument.

(note setjmp needn't functions; may macro. longjmp function, though.)

use cases cited "error handling", , "don't use these functions".

here's little control flow example:

jmp_buf env;  void foo() {     longjmp(&env, 10);                      +---->----+ }                                           |         |                                             |         | int main()              (entry)---+         ^         v {                                 |         |         |     if(setjmp(&env) == 0)         | (= 0)   |         | (= 10)     {                             |         ^         |         foo();                    +---->----+         |     }                                                 +---->----+     else                                                        |     {                                                           |         return 0;                                               +--- (end)     } } 

notes:

  • you cannot pass 0 longjmp. if do, 1 returned setjmp.

  • you must not return function called setjmp before corresponding longjmp. in other words, longjmp must called above setjmp in call stack.

  • (thanks @wildplasser:) cannot store result of setjmp. if want return in several different ways, can use switch, though:

    switch (setjmp(&env)) { case 0:   // first call case 2:   // returned longjmp(&env, 2) case 5:   // returned longjmp(&env, 5) // etc. } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -