Skip to content

Instantly share code, notes, and snippets.

@robrighter
Created May 13, 2012 01:35
Show Gist options
  • Save robrighter/2670140 to your computer and use it in GitHub Desktop.
Save robrighter/2670140 to your computer and use it in GitHub Desktop.
Using the C Preprocessor for easy iterating
#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