Just out of curiosity, I\'d like to know if it is possible to define a macro which can turn its argument into a character literal:
switch(getchar()) {
ca
While I couldn't get user4098326's answer to compile, I did get the solution below to compile and work as expected (in Code Composer Studio). The key was to use the symbol concatenation operator. Note however, that according to the standard, this should not work. A single quote (') is not a valid token nor is a single quote followed by a single character ('a). Thus those should not be able to be the input nor output of the concatenation operator. Thus, I would not recommend actually using this solution.
#define CONCAT_H(x,y,z) x##y##z
#define SINGLEQUOTE '
#define CONCAT(x,y,z) CONCAT_H(x,y,z)
#define CHARIFY(x) CONCAT(SINGLEQUOTE , x , SINGLEQUOTE )
#define DO_CASE(...) case CHARIFY(__VA_ARGS__): printf("Got a " #__VA_ARGS__ "\n"); break
Then:
switch(getchar()) {
DO_CASE(A);
DO_CASE(a);
DO_CASE(!);
default: printf("Neither a nor A nor !\n"); break;
}
Here's my possible solution:
#define EVAL(...) __VA_ARGS__
#define Q() '
#define MYMACRO(...) Q()EVAL(__VA_ARGS__)Q()
(Variadic macros are used to to support MYMACRO(,)
because it would be parsed as two empty arguments.)
I'm not sure if this code is standard-conformant due to the unmatched '
.
Still, I think this code works on most C99 compilers.
However, this code does not work for the following characters:
(
which has to match with )
)
used to identify the start and end of the argument list'
and "
used for string literals and character constants\
, which needs escapingI'm fairly sure that there's no solution that work for (
, )
, '
or "
, because if this was allowed, the compiler would have to change the way macros arguments are parsed.