P
Player
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 }
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 }