fork download
  1. #include <stdio.h>
  2.  
  3.  
  4. #define BEGIN switch (ctx->state) { \
  5.   case 0:
  6.  
  7. #define YIELD(val) do { \
  8.   ctx->state = __LINE__; \
  9.   return val; \
  10.   case __LINE__: \
  11.   ; \
  12.   } while (0)
  13.  
  14. #define END }
  15.  
  16. typedef struct{
  17. int state;
  18. int i;
  19. } Ctx;
  20.  
  21. int foo(Ctx* ctx)
  22. {
  23. BEGIN;
  24. while (1) {
  25. printf("foo suspending...\n");
  26. YIELD(++ctx->i);
  27. printf("foo resumed\n");
  28. }
  29. END;
  30. return 0;
  31. }
  32.  
  33. int main()
  34. {
  35. int i=0;
  36.  
  37. Ctx t0 = {0,1};
  38. while (i = foo(&t0)) {
  39. printf("val: %d\n", i);
  40. if (i > 10) {
  41. printf("enough\n");
  42. break; // ideone can't run program indefinitely
  43. }
  44. }
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 5564KB
stdin
Standard input is empty
stdout
foo suspending...
val: 2
foo resumed
foo suspending...
val: 3
foo resumed
foo suspending...
val: 4
foo resumed
foo suspending...
val: 5
foo resumed
foo suspending...
val: 6
foo resumed
foo suspending...
val: 7
foo resumed
foo suspending...
val: 8
foo resumed
foo suspending...
val: 9
foo resumed
foo suspending...
val: 10
foo resumed
foo suspending...
val: 11
enough