Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Last active September 4, 2022 13:51
Show Gist options
  • Save crosstyan/0d34e0c7ac332ad7f0f043d773ae8ce9 to your computer and use it in GitHub Desktop.
Save crosstyan/0d34e0c7ac332ad7f0f043d773ae8ce9 to your computer and use it in GitHub Desktop.
an example to use iterator instead of ugly fuck i. See also https://crypto.stanford.edu/~blynn/c/cruft.html
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#define REP(x, n) for (int x = 0; x < n; x++)
#define REP1(x, n) for (int x = 1; x <= n; x++)
#define NELEM(a) (sizeof(a)/sizeof(a[0]))
struct test_t {
int * arr;
size_t size;
};
struct test_t new_test(size_t n) {
int * p = malloc(n * sizeof(int));
/* a better way to restrict local variable if you really wanted to */
/* https://stackoverflow.com/questions/2687392/is-it-possible-to-declare-two-variables-of-different-types-in-a-for-loop */
for (struct {int idx; int * it; } s = { 0, p }; s.it < p + n; s.idx++, s.it++) {
*s.it = s.idx;
}
struct test_t t = (struct test_t) {
.arr = p,
.size = n
};
return t;
}
static inline int * test_begin(struct test_t *t){
return t->arr;
}
static inline int * test_end(struct test_t *t){
return t->arr + t->size;
}
int main() {
struct test_t arr[3] = {
new_test(3),
new_test(10),
new_test(2)
};
for (struct {int idx; struct test_t * it;} s = {0, arr}; s.it < arr + NELEM(arr); s.idx++, s.it++) {
printf("idx: %d, size: %d\n", s.idx, (int) s.it -> size);
for (struct { int at; int * it; } i = {0, test_begin(s.it)}; i.it < test_end(s.it); i.at++, i.it++) {
printf("idx: %d, value at %d is %d\n", s.idx, i.at, *i.it);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment