T
the.theorist
I was implementing the traditional FOREACH macro, and noticed that in
C99 mode the usual int used for iteration must be declared prior to
the for loop. This means that my macro must declare a variable in an
outer scope. In order to avoid scope pollution, I'm wondering if there
is a way to coerce the preprocessor into creating unique names. Let me
demonstrate what I mean:
My macro:
#define FOREACH(p, set) \
int _i = 0; \
for (p = (set)->pset[_i]; \
_i<(set)->num; \
++_i) \
It's clear that in any scope I use this macro, a int variable by the
name _i will be created. Though I'm reasonably sure that this will not
be a problem if I use the macro multiple times in the same scope, or
choose to nest the FOREACH's, I'm still curious about how I could get
the preprocessor to generate a unique name for _i, so as to avoid any
possible aliasing.
My first thought was to use the __LINE__ directive and ##
concatenation. My plan was for the iteration variable to be named
_i610 if the FOREACH macro occured on line 610 in the source. For my
purposes, using line numbers will be unique enough. Unfortunately, the
preprocessor doesn't expand the __LINE__ and the variable name came
out as _i__LINE__. So my question for the group: Is there a way to get
the c preprocessor to generate unique names?
C99 mode the usual int used for iteration must be declared prior to
the for loop. This means that my macro must declare a variable in an
outer scope. In order to avoid scope pollution, I'm wondering if there
is a way to coerce the preprocessor into creating unique names. Let me
demonstrate what I mean:
My macro:
#define FOREACH(p, set) \
int _i = 0; \
for (p = (set)->pset[_i]; \
_i<(set)->num; \
++_i) \
It's clear that in any scope I use this macro, a int variable by the
name _i will be created. Though I'm reasonably sure that this will not
be a problem if I use the macro multiple times in the same scope, or
choose to nest the FOREACH's, I'm still curious about how I could get
the preprocessor to generate a unique name for _i, so as to avoid any
possible aliasing.
My first thought was to use the __LINE__ directive and ##
concatenation. My plan was for the iteration variable to be named
_i610 if the FOREACH macro occured on line 610 in the source. For my
purposes, using line numbers will be unique enough. Unfortunately, the
preprocessor doesn't expand the __LINE__ and the variable name came
out as _i__LINE__. So my question for the group: Is there a way to get
the c preprocessor to generate unique names?