Another c iterator

Discussion

i found that i needed someway to iterate though most of my data structures, i didn't really want to use void* everywhere, so i came up with a macro which generates a struct that contains a user provided struct and then uses the user defined functions on them to iterate and provide a value to the inner loop. for break and continue to work it toggles a flag in both of the enerated loops

```c

#define FOREACH_DROP_ARGS(...)

#define FOREACH_getInit_struct(init, ...) init

#define FOREACH_getInit_set(init, ...) __VA_ARGS__

#define FOREACH_getInit(init, next, check, cast) init

#define FOREACH_getNext(init, next, check, cast) next FOREACH_DROP_ARGS

#define FOREACH_getCheck(init, next, check, cast) check FOREACH_DROP_ARGS

#define FOREACH_getCast(init, next, check, cast) cast FOREACH_DROP_ARGS

#define foreach(declaration, generator) \

for ( \

struct { \

char cond; \

MACRO_FROEACH_EXPAND(FOREACH_getInit_struct FOREACH_getInit FOREACH_##generator) \

_foreach_; \

} _foreach_ = { \

.cond = 1, \

._foreach_ = MACRO_FROEACH_EXPAND(FOREACH_getInit_set FOREACH_getInit FOREACH_##generator), \

}; \

MACRO_FROEACH_EXPAND(/**/ \

FOREACH_getCheck FOREACH_##generator \

)(_foreach_._foreach_) && \

_foreach_.cond; \

(_foreach_.cond = !_foreach_.cond, /**/ \

MACRO_FROEACH_EXPAND( /**/ \

FOREACH_getNext FOREACH_##generator \

)(_foreach_._foreach_))) \

for ( \

declaration = \

MACRO_FROEACH_EXPAND( \

FOREACH_getCast FOREACH_##generator \

)(_foreach_._foreach_); \

_foreach_.cond; \

_foreach_.cond = !_foreach_.cond)
```
some examples in godbolt

Posted Aug 13, 2026, 5:02 PM UTC

00
Loading comments…