Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!pacbell.com!att!rutgers!ucsd!mvb.saic.com!ncr-sd!ncrcae!secola!jmartin From: jmartin@secola.Columbia.NCR.COM (John Martinez) Newsgroups: comp.lang.c Subject: You _CAN_ "stringize" tokens in (some) K&R pre-processors Message-ID: <323@secola.Columbia.NCR.COM> Date: 2 Apr 91 00:21:14 GMT Reply-To: jmartin@secola.Columbia.NCR.COM (John V. Martinez) Distribution: comp.lang.c Organization: NCR NPD Columbia Lines: 64 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@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@secola.Columbia.NCR.COM (803)772-8854 vplus:633-8854