Skip to content

Instantly share code, notes, and snippets.

@abhinavsingh
Created May 12, 2015 08:15
Show Gist options
  • Save abhinavsingh/2e6b1a3bf87e588eb222 to your computer and use it in GitHub Desktop.
Save abhinavsingh/2e6b1a3bf87e588eb222 to your computer and use it in GitHub Desktop.
Python style range function in C as macro
#include <setjmp.h>
void generator();
jmp_buf buf;
#define YIELD(i) longjmp(buf, i)
#define FOR_RANGE(v,n) { \
int v=0; \
while(v!=n) { \
v = setjmp(buf); \
if (v == 0) { \
generator(); \
} \
else {
#define END_RANGE }}}
void generator() {
static int i=0;
i++;
YIELD(i);
}
#include <stdio.h>
#include "for_range.h"
int main() {
FOR_RANGE(i, 5)
printf("%d\n", i);
END_RANGE
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment