[<<][c][>>][..]
Thu Feb 19 17:41:02 CET 2009

C macros and name capture

Today I spent an hour tracking down a classic bug: hygiene problems
with non-hygienic macros (C preprocessor).  See the following
definition, call and expansion:

// definition
#define LST_ADD(head_lvalue, tail) {\
        typeof(head_lvalue) *p = &(head_lvalue);        \
        while(*p) { p = &((*p)->next); }                \
        *p = tail; }

// call
LST_ADD(m->param_head, p);

// expansion
{ 
     typeof(m->param_head) *p = &(m->param_head); 
     while(*p) { p = &((*p)->next); } 
     *p = p; 
};        

The introduced symbol "p" shadows the variable "p" in the calling
context.  This can be avoided by always binding all macro input names
to local variable names before introducing macro-local names, but it's
sufficient to bind those that might be shadowed by the introduced
binding, which depends on how they are used.

// new definition
#define LST_ADD(head_lvalue, tail) {\
        typeof(tail) _tail = tail; {\
        typeof(head_lvalue) *p = &(head_lvalue);        \
        while(*p) { p = &((*p)->next); }                \
        *p = _tail; }}




[Reply][About]
[<<][c][>>][..]