问题
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
回答1:
–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.
回答2:
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?
回答3:
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.
来源:https://stackoverflow.com/questions/26140446/macro-string-literal-from-char-literal