Skip to content

Instantly share code, notes, and snippets.

@debuti
Last active August 5, 2019 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debuti/42378eb8a8ecc0ea728ac5242376234a to your computer and use it in GitHub Desktop.
Save debuti/42378eb8a8ecc0ea728ac5242376234a to your computer and use it in GitHub Desktop.
Loop on generic type len array
#include <stdio.h>
#define LOOP_ON_GENERIC(T, A, AL, I) \
T* I = NULL; \
T** I##_p = NULL; \
if (A) \
for(I##_p = A, I = *I##_p; \
I##_p < A + AL; \
I##_p++, I = (I##_p < A + AL ? *I##_p:NULL))
struct t {
int xx;
char yy;
};
void main() {
/* Lets do easy with some chars */
char a = 'a';
char b = 'b';
char c = 'c';
char* x[] = {&a, &b, &c};
size_t x_len = 3;
LOOP_ON_GENERIC(char, x, x_len, e) {
printf("now at item %c\n", *e);
}
/* What if empty? */
char** y = NULL;
size_t y_len = 0;
LOOP_ON_GENERIC(char, y, y_len, f) {
printf("now at item %c\n", *e);
}
/* Why not something more complex */
struct t ta = {.xx=10, .yy='A'};
struct t tb = {.xx=12, .yy='A'+2};
struct t tc = {.xx=14, .yy='A'+4};
struct t td = {.xx=16, .yy='A'+6};
struct t* tx[] = {&ta, &tb, &tc, &td};
size_t tx_len = sizeof(tx)/sizeof(struct t*);
LOOP_ON_GENERIC(struct t, tx, tx_len, q) {
printf("now at item %d %c\n", q->xx, q->yy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment