Re: Generic list push/pop

Daniel Phillips (phillips@arcor.de)
Tue, 20 Aug 2002 17:30:28 +0200


On Tuesday 20 August 2002 15:08, Thunder from the hill wrote:
> ...Anyway, this work had already been done by
> Thomas 'Dent' Mirlacher. We might want to work on that.
>
> [...]
>
> +#define slist_add_front(_new, _head) \
> +do { \
> + _new->next = _head; \
> + _head = _new->next; \
> +} while (0)

The second line is equivalent to _head = _head.

> +#define slist_add(_new, _head) \
> +do { \
> + _new->next = _head->next; \
> + _head->next = _new; \
> +} while (0)

I don't see the point of this. Why doesn't the caller just push_list onto
head->next?

Anyway, since I went to the trouble of writing versions of push/pop_list
that at least avoid multiple argument evaluation, here they are in all their
glorious ugliness:

#define push_list(list, node) do { \
typeof(list) *_LIST_ = &(list), _NODE_ = (node); \
_NODE_->next = *_LIST_; \
*_LIST_ = _NODE_; } while (0)

#define pop_list(list) ({ \
typeof(list) *_LIST_ = &(list), _NODE_ = *_LIST_; \
*_LIST_ = (*_LIST_)->next; \
_NODE_; })

It's unecessary to obfuscate the macro parameter names. On the other hand,
if somebody passes in an expression that happens to contain one of the
obfuscated local variable names, bad things will happen. On the third hand,
if somebody does that they probably need bad things to happen to them.

This problem arises only because of C's idiotic policy of entering the new
local symbol before parsing the initializer, and there is nothing you can do
about it[1] except to avoid using obfuscated variable names in normal code,
and check carefully for nested obfuscated variables every time you write a
macro.

The other problems with these constructions are:

- How do we know gcc will successfully optimize these things to the
same code you'd get if you simply wrote the two required assignments
out in full? The local variables should disappear early in constant
expression evaluation, but do they always?

- We assume the link field is named 'next'.

- They are ugly (but I don't care. If you need to feast your eyes on
ugly, look at any pgtable.h)

As promised, I moved them to my scraps.c and just wrote the code out in full.

[1] If we uniformly adopt the convention of encoding the name of the macro
into any locals declared in macros, plus a convention to indicate the end of
name, I suppose we could gaurantee uniqueness. Or we can just keep muddling
along as usual (more likely).

-- 
Daniel
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/