How evil is this foreach C macro?

The preface to this question is that I understand that C macros are a touchy subject. They can be achieved a lot of time with a non-macro solution, which is safer and not prone to classical problems, such as additional arguments; so with that in mind, I have a hash table implementation in C with related nodes for collision. I'm sure most of them have seen it a million times, but it looks a bit like this.

typedef struct tnode_t {
    char* key; void* value; struct tnode_t* next;
} tnode_t;

typedef struct table_t {
    tnode_t** nodes;
    unsigned long node_count;
    unsigned long iterator; // see macro below
        ...
}

I would like to provide an abstract way of iterating through nodes. I considered using a function that takes a pointer to a function and applies the function to each node, but I often find this solution very limited, so I came up with this macro:

#define tbleach(table, node) \
    for(node=table->nodes[table->iterator=0];\
        table->iterator<table->node_count;\
        node=node?node->next:table->nodes[++table->iterator])\
            if (node)

:

tnode_t* n;
tbleach(mytable, n) {
    do_stuff_to(n->key, n->value);
}

, , - , , , , . , , , , . .

** **

Zack Jens, "else" for. , , " ", . , , , , .

#define tbleach(table, node) \
    for(node=table->nodes[0], unsigned long i=0;\
        i<table->node_count;\
        node=node?node->next:table->nodes[++i])\
        if (!node) {} else

, , ?

+3
2

, - . :

typedef unsigned long table_iterator_t;
#define tbleach(table, iter, node) \
    for ((iter) = 0, (node) = (table)->nodes[(iter)]; \
         (iter) < (table)->node_count; \
         (node) = ((node) && (node)->next) \
                  ? (node)->next : (table)->nodes[++(iter)])

// use:
table_iterator_t i;
tnode_t *n;
tbleach(mytable, i, n) {
    do_stuff_to(n->key, n->value);
}

if , ( , else). , table->nodes[table->node_count] , , ( , NULL). , .

EDIT: ​​ , NULL.

+7

Zack if, :

C99, for. , . - :

for(nodeS node = ...

, _t POSIX. .

+1

Source: https://habr.com/ru/post/1793077/


All Articles