lvella lvella - 1 year ago 36
C Question

Is this code valid?

For compatibility reasons, I want to define an iterator macro that works like this:

elem_type *ptr;
ITERATE(&container, ptr) {
// This will loop through every element of the container
// ptr will point to the current element.

I have an iterator type that must be initialized with a function call, and works like this:

iter_type iter;
iter_init(&container, &iter);
while((ptr = iter_next(&iter))) {
// ...

So, this is the solution I came up to squeeze this sequence into the macro:

#define ITERATE(container_ptr,elem_ptr) \
for(iter_type _iter = ( \
iter_init(container_ptr, &_iter), _iter); \
(elem_ptr = iter_next(&_iterator));)

So, as you can see, there is a little trick with the comma operator, in order to fit both a variable declaration and the function call initialization in the first colon of the
. Is this code valid C99, and will always work?

Answer Source

Yes, it's valid and will always work.

Just taking your for loop,

    for(iter_type _iter = (iter_init(container_ptr, &_iter), _iter); \
        (elem_ptr = iter_next(&_iterator));)

and specifically the initialization clause iter_type _iter = (iter_init(container_ptr, &_iter), _iter), you can see that the comma operator is involved here.

The comma operator always evaluated left to right and there's a sequence between each of its operands.