Created
May 12, 2015 08:15
-
-
Save abhinavsingh/2e6b1a3bf87e588eb222 to your computer and use it in GitHub Desktop.
Python style range function in C as macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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