Preprocessor macro to quote its argument

Barton E. Schaefer schaefer at ogicse.ogi.edu
Tue Aug 21 00:22:30 AEST 1990


In article <1114 at mti.mti.com> adrian at mti.UUCP (Adrian McCarthy) writes:
} In article <1112 at mti.mti.com> adrian at mti.UUCP I wrote:
} >Ever needed a preprocessor macro that could quote its argument?  [...]
} >	#define Q	"
} >	#define Q1(x)	Q x "
} 
} It has been pointed out by several kind folks that this is *not*
} ANSI-compliant.  ANSI preprocessors do the tokenization of the input for
} the rest of the compiler (thus ``preprocessor'' is arguably a misnomer),
} so the #define lines would generate errors since the unpaired double-quote
} is an incomplete token.

In article <1990Aug20.012839.3545 at zoo.toronto.edu> henry at zoo.toronto.edu (Henry Spencer) writes:
} 
} Actually, a good many pre-ANSI preprocessors do this too; X3J11 did not
} invent this approach.

Now wait a minute here -- is it really true that the "right hand side"
of a #define constant must be a valid token sequence?  I was under the
impression that only the result after expansion had to be a valid sequence.

I believe that someone once suggested quoting a single character by

#define C1(x) 'x
#define C2(x) x'
#define CHAR(x) C2(C1(x))

and I don't recall any complaints about 'x and x' not being tokens coming
up at that point.  That was in a discussion of how to repair macros that
(in Reiser cpp) use stuff like

#define CTRL(x) ('x' & 037)
char eof = CTRL(D);

by using instead

#define CTRL(x) (CHAR(x) & 037)

for an ANSI preprocessor.  Yes, I know the preferred method would be
either ( #x [0] & 037) or global replacement to use CTRL('D').  The
question is, is   #define C1 'x   an error at time of definition?
-- 
Bart Schaefer						schaefer at cse.ogi.edu



More information about the Comp.lang.c mailing list