How to single-quote an argument in a macro?

假如想象 提交于 2019-11-29 06:31:32

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).

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]);

The best I can think of would be

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

but this isn't very pretty, admittedly.

this generates conversions:

#python
for i in range(ord('a'), ord('n')):
    print "#define BOOST_PP_CHAR_%s '%s'" % (chr(i), chr(i))

and this is preprocessor part:

#ifndef BOOST_PP_CHAR_HPP
#define BOOST_PP_CHAR_HPP

#define BOOST_PP_CHAR(c) BOOST_PP_CHAR_ ## c
//  individual declarations    

#endif // BOOST_PP_CHAR_HPP

I've just tried concatenation:

#define APOS           '
#define CHAR2(a,b,c)   a##b##c
#define CHAR1(a,b,c)   CHAR2(a,b,c)
#define CHAR(x)        CHAR1(APOS,x,APOS)

Unfortunately though, the preprocessor complains about an unterminated character. (and multicharacter if you have more than one character) A way to just disable preprocessor errors: (there is no specific warning option for this)

-no-integrated-cpp -Xpreprocessor -w

Some compile-time optimization example with some other tricks:

#define id1_id       HELP
#define id2_id       OKAY

#define LIST(item,...) \
    item(id1, ##__VA_ARGS__)\
    item(id2, ##__VA_ARGS__)\
    item(id1, ##__VA_ARGS__)\

#define CODE(id,id2,...)    ((CHAR(id##_id) == CHAR(id2##_id)) ? 1 : 0) +
int main() { printf("%d\n", LIST(CODE,id1) 0); return 0; }

This returns "2", since there are two items that have id1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!