#include #include int fn1, fn2, state = 1; int fib_gvar() { int fn; choose ( state ) { case 1: fn = 0; fn1 = fn; state = 2; case 2: fn = 1; fn2 = fn1; fn1 = fn; state = 3; case 3: fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return fn; } #define FIB_INIT { 0, 1 } typedef struct { int fn1, fn2; } Fib; int fib_state( Fib & f ) with( f ) { int ret = fn2; int fn = fn1 + fn2; fn2 = fn1; fn1 = fn; return ret; } coroutine Fib1 { int fn; }; // used for communication void main( Fib1 & fib ) with( fib ) { // called on first resume fn = 0; int fn1 = fn; suspend(); fn = 1; int fn2 = fn1; fn1 = fn; suspend(); for () { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; suspend(); } } int next( Fib1 & fib ) with( fib ) { resume( fib ); return fn; } coroutine Fib2 { int ret; }; // used for communication void main( Fib2 & fib ) with( fib ) { // called on first resume int fn, fn1 = 1, fn2 = 0; // precompute first two states for () { ret = fn2; fn = fn1 + fn2; fn2 = fn1; fn1 = fn; // general case suspend(); // restart last resume } } int next( Fib2 & fib ) with( fib ) { resume( fib ); // restart last suspend return ret; } int main() { for ( 10 ) sout | fib_gvar(); sout | nl; Fib f1 = FIB_INIT, f2 = FIB_INIT; for ( 10 ) sout | fib_state( f1 ) | fib_state( f2 ); sout | nl; Fib1 f1, f2; for ( 10 ) sout | next( f1 ) | next( f2 ); sout | nl; Fib2 f1, f2; for ( 10 ) sout | next( (Fib2 &)f1 ) | next( (Fib2 &)f2 ); } // Local Variables: // // tab-width: 4 // // fill-column: 120 // // compile-command: "cfa Fib.cfa" // // End: //