You _CAN_ "stringize" tokens in (some) K&R pre-processors
John Martinez
jmartin at secola.Columbia.NCR.COM
Tue Apr 2 10:21:14 AEST 1991
I seem to recall a thread of discussion a couple of weeks ago
about how to "stringize" a token using the K&R C preprocessor (ANSI C
provides the # operator to do this.) Anyway, as I recall, the concensus
was that it couldn't be done. (At least, no one submitted a method, as
far as I know...)
Well, now I had to try (the Mt. Everest principle, you know,)
so I locked myself in my laboratory with a six-pack of Mountain Dew and
a cold pizza, until I discovered a magic spell that (sort of) did the
trick:
#define quote "
#define stringize(A) quote A"
this is _almost_ right; stringize(foobar) --(magic)--> " foobar"
The next problem is to remove the leading space (if you don't
put a space between 'quote' and 'A' in the macro, it sees 'quoteA' as a
token, which doesn't resolve to anything interesting..)
Another slice of cold pizza later.....
-(POOF)-
*********
static char *global_char_ptr; /* 'static' is just a personal preference. */
#define quote "
#define stringize(a) (global_char_ptr=quote a",++global_char_ptr)
main()
{
int foo=5;
printf("%s = %d\n",stringize(foo),foo);
}
*********
_my_ system's preprocessor converts the printf line to:
printf("%s = %d\n",(global_char_ptr=" foo",++global_char_ptr),foo);
which outputs:
foo = 5
Voila!
NOTE: I'm sure there are lots of netters who:
a) already knew about this
b) saw a solution just like it in a posting I never saw
_or_
c) think the whole discussion is dumb since "the whole world should have
bought an ANSI C compiler 4.7 microseconds after the standards were
signed, no matter what the cost, and if you can't find a compiler you
can just write your own in 2 hours, otherwise you're not a real programmer"
I have a established a special account, devnull at TheAbyss for
you to reply by mail. Seriously - I posted this because I thought it
would be of use to someone, and I am pretty darn happy about it, so
don't rain on my parade, ok?
---
John V.Martinez "Yeah, I got a college degree, but somehow I
NCR Network Products Division managed to learn something in spite of it."
jmartin at secola.Columbia.NCR.COM
(803)772-8854 vplus:633-8854
More information about the Comp.lang.c
mailing list