tags:

views:

210

answers:

3

I would like to create a C pre-processor macro that will single-quote the argument. Just like the common used #X.

I want Q(A) to be expanded to 'A'.

I am using gcc on Linux.

Does any one have an idea?

I know # double-quotes. I am looking for a similar mechanism fir single-quoting.

+3  A: 

The best I can think of would be

#define Q(A) (#A[0])

but this isn't very pretty, admittedly.

Joey
+6  A: 

The best you can do is

#define Q(x) ((#x)[0])

or

#define SINGLEQUOTED_A 'A'
#define SINGLEQUOTED_B 'B'
...
#define SINGLEQUOTED_z 'z'

#define Q(x) SINGLEQUOTED_##x

This only works for a-z, A-Z, 0-9 and _ (and $ for some compilers).

KennyTM
Oh, that second method is pure evil ;-)
Joey
`$` is not a valid character for an identifier, according to the C standard. It may be accepted by some specific compilers, I suppose.
Dale Hagglund
@Dale: Yes, GCC supports `$` as an identifier. http://gcc.gnu.org/onlinedocs/gcc/Dollar-Signs.html#Dollar-Signs
KennyTM
Dale: Well, the standard allows for implementation-defined characters beyond digits, ASCII letters and the underscore. But that's probably not very portable, then :)
Joey
+1  A: 

Actually, #X double quotes its argument, as you can see with the following code.

#define QQ(X) #X
char const * a = QQ(A);

Run this with gcc -E (to just see the preprocessor output) to see

# 1 "temp.c"
# 1 "<built-n>"
# 1 "<command line>"
# 1 "temp.c"

char * a = "A"

To single quote your argument (which in C means that it's a single character) use subscripting

#define Q(X) (QQ(X)[0])
char b = Q(B);

which will be transformed into

char b = ("B"[0]);
rampion