On 1/3/2013 1:11 PM, Player wrote:
> I'm not quite familiar with setjmp/longjmp (and neither with macros either) but I was trying to make something similar to this "yielding return" construct from C#, namely: when a function X "yields returns" some value everything happens like it has actually returned that value; however the state (local vars, IP) is saved, so that when X is called again it starts execution in the next statement after the last "yield return".
>
> Is this a portable legal solution, as long as I keep local variables volatile:
> 1 #include <stdio.h>
> 2 #include <setjmp.h>
> 3 #define STATE_FUNC static jmp_buf _env; static int first_time = 1; if (first_time) first_time = 0; else longjmp(_env, 1)
> 4 #define yield(X) do { if (!setjmp(_env)) return X; } while(0)
> 5
> 6 int next_integer()
> 7 {
> 8 STATE_FUNC;
> 9 while(1) {
> 10 yield(1);
> 11 yield(2);
> 12 yield(3);
> 13 }
> 14 }
> 15
> 16
> 17 int main()
> 18 {
> 19 int p = 20;
> 20 while(p--) printf("%d", next_integer());
> 21 return 0;
> 22 }
No: The `return' actually returns, destroying its function's
entire invocation and all the context that accompanies it. When
the function is re-entered a brand-new invocation begins, having
no connection to the previous one. You cannot expect longjmp()
to restore all of a destroyed context.
Concrete example: On many systems, entering a function reserves
a greater or lesser amount of stack space for the function's use.
Returning releases that space, allowing subsequent functions (or
the system itself) to use it. When your next_integer() function
releases its stack space, printf() and all the things printf()
calls are at liberty to reserve it, use it, and release it in
their turn. Re-entering next_integer() will reserve the space
again (or perhaps an equivalent amount of space at some other
memory address!), but it may have been scribbled on in the meantime
and anything the prior next_integer() invocation may have stored
there -- like `volatile' variables -- may well be garbage.
What problem are you trying to solve?
--
Eric Sosman
d