Macro: string literal from char literal

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

for example me

'a' 

and I want to create a string literal

 "a" 

To clarify the question:

 #define A 'a' write(fd, "x=" CHAR2STRING(A) "\n", 4); 

My question is how to define the CHAR2STRING macro

+7
c c-preprocessor
source share
3 answers

- The materiality of the comments on the question -

It seems impossible. Alternatively, a string literal can be defined instead of the STRING2CHAR macro:

 #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" not a compile-time constant (therefore, for example, it cannot be used as an initializer for an object with non-automatic storage duration, non-VLA array length, case label, or bit field width), although compilers should be able to evaluate it at compile time (checked with Gcc and Clang).


Offered by M Oehm and Matt McNabb .

+2
source share

Not very elegant, but it works:

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

Assumes tgt has space for 2 characters. Perhaps you could give an example of how you want it to look?

0
source share

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 this is normal for you.

0
source share

All Articles