macro: string literal from char literal

2019-06-17 05:58发布

Is there a way in C to create a string literal from a character literal, using a macro?

for example I have

'a'

and I want to create the string literal

"a"

To clarify the question:

#define A 'a'

write(fd, "x=" CHAR2STRING(A) "\n", 4);

My question is how to define the macro CHAR2STRING

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-17 06:30

You could do

#define A 'a'
#define X(macro) #macro
#define CHAR2STRING(macro) X(macro)

printf("%s\n", CHAR2STRING(A));

you will get 'a' instead of a, but maybe thats ok for you.

查看更多
相关推荐>>
3楼-- · 2019-06-17 06:31

Not very elegant, but it works:

#define STRING_ME(tgt, ch) tgt[0]=ch;tgt[1]='\0'

Assumes tgt has space for 2 chars. Perhaps you could give an example what you want it to look like?

查看更多
放我归山
4楼-- · 2019-06-17 06:34

–Summary of the comments to the question–

This seems impossible to achieve. As an alternative, the string literal could be defined and a STRING2CHAR macro be written instead:

#define A "a"
#define STRING2CHAR(s) (*(s))
write(fd, "x=" A "\n", 4);
putchar(STRING2CHAR(A));

or

#define A a
#define XSTR(s) #s
#define SYM2CHAR(sym) (*XSTR(sym))
#define SYM2STRING(sym) XSTR(sym)

The expression *"a" isn't a compile-time constant (so e.g. it cannot be used as an initializer for an object with non-automatic storage duration, a non-VLA array length, a case label, or a bit-field width), though compilers should be able to evaluate it at compile-time (tested with Gcc and Clang).


Suggested by M Oehm and Matt McNabb.

查看更多
登录 后发表回答