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()) {
case MYMACRO(A): printf("Received A\n"); break;
case MYMACRO(a): printf("Received a\n"); break;
case MYMACRO(!): printf("Received an exclamation mark\n"); break;
default: printf("Neither a nor A nor !\n"); break;
}
Two possible solutions off the top of my head:
Enumerating all characters
#define LITERAL_a 'a'
#define LITERAL_b 'b'
...
#define MYMACRO(x) LITERAL_ ## x
It doesn't work with MYMACRO(!)
because !
is not a valid component of a C identifier.
Convert the parameter into a string literal
#define MYMACRO(x) #x [0]
It involves a pointer dereference and is invalid in places like a case label.
I'm not asking for a way to "improve" the above switch statement itself. It's just a toy example. Repeat. It's just a toy example.