Preprocessor Trickery - (nf)

jim at ism780b.UUCP jim at ism780b.UUCP
Thu Aug 2 14:18:18 AEST 1984


#R:elsie:-101400:ism780b:25500010:000:1888
ism780b!jim    Jul 17 21:58:00 1984

>
>         >Try typing this to see what happens:
>         >       cc -E -
>         >       #define Ident(xxx) xxx
>         >       #define concat(a,b) Ident(a)b
>         >       __LINE__
>         >       concat(__LINE__,__LINE__)
>
> "concat(__LINE__,__LINE__)" gives "__LINE____LINE__"
> "concat(__LINE__, __LINE__)" gives, e.g.,  "3 3"

Not with a Reiser cpp (this is just one of the hundreds of bugs;
I too rolled my own).

>For that matter:        "concat(this,that)" results in "thisthat"
>                        "concat(this, that)" results in "this that"

Easy to explain: the arguments to a macro consist of the text between
parens and commas (not nested within parens), including any white space.
Thus, you concatenated "this" with " that".  The problem is that there
is no formal documentation of cpp.

> Defining "concat(a, b)" instead of "concat(a,b)" doesn't, however, seem to
> make a difference.

Of course, since "a" and "b" are just tokens to be replaced in the replacement
text.

> It *is* interesting behavior.

Not very.

> And also reinforces my
> general feelings that:  (a) relying on the preprocessor to do too much for you
> is foolish, and (b) being very clever is a really fun way to screw up those
that follow you (or yourself when you have to go back to the miserable thing
two years later and have forgotten how terribly clever you were), especially
when you follow the customary C commenting conventions.

Definitely true given that it is undocumented, although understandable when
the only alternative is m4.  When defining a macro which can be tucked away
in a common include file with plenty of comments can allow you to write
far more readable and modifiable code elsewhere, then it may not be so
foolish.  However, if it is just used to support another favorite hack,
then the cause is lost anyway.

-- Jim Balter, INTERACTIVE Systems (ima!jim)



More information about the Comp.lang.c mailing list