Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The C99 spec gives:</p> <blockquote> <p>If the return is from a direct invocation, the setjmp macro returns the value zero. If the return is from a call to the longjmp function, the setjmp macro returns a nonzero value.</p> </blockquote> <p>So the answer to 1 is that a zero indicates you have called <code>setjmp</code> the first time, and non-zero indicates it is returning from a <code>longjmp</code>.</p> <ol start="2"> <li><p>It pushes the current program state. After a longjmp, the state is restored, control returns to the point it was called, and the return value is non-zero.</p></li> <li><p>There are no exceptions in C. It's sort-of similar to <code>fork</code> returning different values depending whether you're in the original process, or a second process which has inherited the environment, if you're familiar with that.</p></li> <li><p><code>try</code>/<code>catch</code> in C++ will call destructors on all automatic objects between the throw and the catch. <code>setjmp</code>/<code>longjmp</code> will not call destructors, as they don't exist in C. So you are on your own as far as calling <code>free</code> on anything you've <code>malloc</code>ed in the mean time.</p></li> </ol> <p>With that proviso, this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;setjmp.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; void foo ( char** data ) ; void handle ( char* data ) ; jmp_buf env; int main () { char* data = 0; int res = setjmp ( env ); // stored for demo purposes. // in portable code do not store // the result, but test it directly. printf ( "setjmp returned %d\n", res ); if ( res == 0 ) foo ( &amp;data ); else handle ( data ); return 0; } void foo ( char** data ) { *data = malloc ( 32 ); printf ( "in foo\n" ); strcpy ( *data, "Hello World" ); printf ( "data = %s\n", *data ); longjmp ( env, 42 ); } void handle ( char* data ) { printf ( "in handler\n" ); if ( data ) { free ( data ); printf ( "data freed\n" ); } } </code></pre> <p>is roughly equivalent to </p> <pre><code>#include &lt;iostream&gt; void foo ( ) ; void handle ( ) ; int main () { try { foo (); } catch (int x) { std::cout &lt;&lt; "caught " &lt;&lt; x &lt;&lt; "\n"; handle (); } return 0; } void foo ( ) { printf ( "in foo\n" ); std::string data = "Hello World"; std::cout &lt;&lt; "data = " &lt;&lt; data &lt;&lt; "\n"; throw 42; } void handle ( ) { std::cout &lt;&lt; "in handler\n"; } </code></pre> <p>In the C case, you have to do explicit memory management (though normally you'd free it in the function which malloc'd it before calling longjmp as it makes life simpler)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload