Embedding macro values in strings
Paul John Falstad
pfalstad at phoenix.Princeton.EDU
Fri Jan 11 19:44:52 AEST 1991
In article <1991Jan10.200806.12745 at grep.co.uk> frank at grep.co.uk (Frank Wales) writes:
>For example, suppose I have foo(__LINE__); in my source, and I want that
>to expand to bar("Line n"); where n is substituted with the actual value
>of __LINE__ at that point. Trying
>
> #define foo(n) bar("Line "#n)
>
>and invoking as foo(10); yields bar("Line 10"); , whereas foo(__LINE__);
>yields bar("Line __LINE__"); .
You realize, of course, that foo(10) would not actually produce:
bar("line 10"),
but will produce:
bar("line " "10")
wish is concatenated into a single string in a later phase of
compilation. Just clarifying that.
Anyway, adding another level of macro expansion does the trick:
#define foo(n) bar("Line "fee(n))
#define fee(X) #X
foo(10)
foo(__LINE__)
This produces the intended result (using gcc):
bar("Line ""10" )
bar("Line ""4" )
--
Paul Falstad, pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
"We could nuke Baghdad into glass, wipe it with Windex, tie fatback on
our feet and go skating." - Air Force Times columnist Fred Reed
More information about the Comp.lang.c
mailing list