Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 890
martinkunev Avatar asked Oct 01 '14 11:10

martinkunev


1 Answers

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

like image 113
2 revs Avatar answered Sep 22 '22 07:09

2 revs