Macro substitution in character literals

Lars Henrik Mathiesen thorinn at rimfaxe.diku.dk
Sat Dec 22 07:07:26 AEST 1990


david at lpi.liant.com (David Michaels) writes:
>mbj at natasha.mach.cs.cmu.edu (Michael Jones) writes:
>> How can I write a macro which produces a character literal containing
>> a macro parameter?  I'd like to be able to write something like:
>>	#define chr(c) 'c'	/* Yes, this is incorrect */
>> which for
>>	chr(z)
>> produces
>>	'z'	

>ANSI C does not support any way do this, ...

More precisely, there is no way a strictly conforming program can do
this. As far as I can tell, a conforming implementation can allow
something like this:

	#define _chr(x,q) q##x##q
	#define chr(x) _chr(x,')

It has to be an implementation that treats an unmatched single-quote
as a preprocessing token by itself (the behaviour is undefined, see
section 3.1). Likewise, it must allow malformed tokens as intermediate
results during token pasting (undefined by 3.8.3.3). In such an
implementation, the code shown does not violate any constraints or
syntax rules. (The constraint in 3.1 talks about the lexical form of
preprocessing tokens converted in translation phase 7, not of their
derivation.)

But I don't think that such an implementation will become common. It
mucks up the scanner (which has to rescan the part of the line after
the unmatched quote), and it conflicts with the GNU C extension of
allowing newlines in character-constants and string-literals.

--
Lars Mathiesen, DIKU, U of Copenhagen, Denmark      [uunet!]mcsun!diku!thorinn
Institute of Datalogy -- we're scientists, not engineers.      thorinn at diku.dk



More information about the Comp.std.c mailing list