Skip to content

Instantly share code, notes, and snippets.

@mfoliveira
Created May 5, 2011 20:07
Show Gist options
  • Save mfoliveira/957805 to your computer and use it in GitHub Desktop.
Save mfoliveira/957805 to your computer and use it in GitHub Desktop.
Yield in C/C++ using Macros
#include "yield.h"
class Fibonacci {
protected:
/* Yield's internal */
void *YIELD_POINTER;
/* Fibonacci terms */
int fib_x, fib_y;
int term;
public:
/* Constructor */
Fibonacci() {
YIELD_POINTER = NULL;
}
/* Function Object */
int operator () (int stop_term) {
yield_start();
/* Seed values */
fib_x = 0;
fib_y = 1;
/* Calculate Fibonacci Numbers */
for (term = 0; term < stop_term; term++) {
/* Fib(0) */
if (term == 0)
yield(0);
/* Fib(1) */
else if (term == 1)
yield(1);
/* Fib(n) */
else {
/* Current term */
int fib_n = fib_x + fib_y;
/* Update previous terms */
fib_x = fib_y;
fib_y = fib_n;
yield(fib_n);
}
}
/* Finished. */
yield_end();
return -1;
}
};
int main() {
/* Print 11 Fibonacci numbers */
Fibonacci fib;
int terms = 11;
int value;
while ( (value = fib(terms)) >= 0 ) {
cout << value << endl;
}
return 0;
}
/* Yield in C/C++ with GNU C Extensions
*
* (C) Copyright 2011, Mauricio Faria de Oliveira
* http://mfoliveira.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
/* Yield Pointer: variable name for storing a re-entry point */
#define YIELD_POINTER __yield_pointer
/* Yield Start:
* If last return is a 'yield' return,
* go to re-entry point.
*/
#define yield_start() \
if ( YIELD_POINTER != NULL ) \
goto *YIELD_POINTER
/* Yield End:
* Set return as 'non-yield' return.
*/
#define yield_end() \
YIELD_POINTER = NULL
/* Yield Point:
* Create a label for a re-entry point.
*
* The extra underscored macros are for
* correct __LINE__ evaluation and concatenation.
*/
#define __yield_point(x, y) \
x ## y
#define _yield_point(x, y) \
__yield_point(x, y)
#define yield_point \
_yield_point(YIELD_POINT_, __LINE__)
/* Yield:
* The trick.
*
* Set return as 'yield' return,
* creating a label after the return statement
* and storing its address for re-entry point.
*/
#define yield(expression) \
do { \
YIELD_POINTER = && yield_point; \
return expression; \
yield_point: ; \
} while (0)
Copy link

ghost commented Sep 30, 2016

This is great. Thank you for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment