Wed Aug 25 14:21:32 CEST 2010

Gensym in C

To make iteration macros for abstract data structures on top of the
`for' keyword, it helps to be able to define unique symbols to store
the iteration state object.  I.e.

#define X_COLLECTION_FOR_(_list, _x, _xl)             \
    struct x_list *_xl;                               \
    for(_xl = (*_list), _x = _xl ? _xl->x : NULL;     \
        _x;                                           \
        _xl = _xl->next, _x = _xl ? _xl->x : NULL)
#define X_COLLECTION_FOR(list, x) X_COLLECTION_FOR_(list, x, __xl__)

The `__xl__' symbol above is inserted into the macro invocation name
context as a local variable and might clash.  Is there a way to
properly solve this problem?

The following seems to work:

#define __GENSYM2(x,y) x##y
#define __GENSYM1(x,y) __GENSYM2(x,y)
#define GENSYM(x) __GENSYM1(x,__COUNTER__)

The indirection is about prescan[3]:

    "If an argument is stringified or concatenated, the prescan does
    not occur. If you want to expand a macro, then stringify or
    concatenate its expansion, you can do that by causing one macro to
    call another macro that does the stringification or concatenation."

[1] http://stackoverflow.com/questions/1132751/how-can-i-generate-unique-values-in-the-c-preprocessor
[2] http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html#Common-Predefined-Macros
[3] http://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan