Created
May 13, 2012 01:35
-
-
Save robrighter/2670140 to your computer and use it in GitHub Desktop.
Using the C Preprocessor for easy iterating
This file contains hidden or 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 <string.h> | |
#include <stdlib.h> | |
//A Preprocessor Macro for iterating | |
#define FOR_EACH(array, type, block) { \ | |
int len = sizeof(array)/sizeof(type);\ | |
for(int i=0; i<len; i++){ \ | |
type this = array[i]; \ | |
block \ | |
} \ | |
} \ | |
int main(int argc, char *argv[]){ | |
//Example 1: Iterate through a list of strings | |
char* array1[] = {"one","two", "three"}; | |
FOR_EACH(array1, char* , { | |
fprintf(stdout, "ITERATE = %s\n", this); | |
}); | |
fprintf(stdout, "\n\n"); | |
//Example 2: Iterate through a list of ints | |
int array2[] = {0,1,2,3,4,5,6,7,8,9}; | |
FOR_EACH(array2, int, { | |
int doubled = this + this; | |
fprintf(stdout, "Doubled Int = %d\n", doubled); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment