Lets say I have this macro
#define last(x) printf("%c", #x[last]);
I want it to print the last char of x, where x is not a string.
How can I get the last char of x ? Is there a short way to do it?
int main(){
last(abc);
}
output: c
Lets say I have this macro
#define last(x) printf("%c", #x[last]);
I want it to print the last char of x, where x is not a string.
How can I get the last char of x ? Is there a short way to do it?
int main(){
last(abc);
}
output: c
Easy to do when we remember that string literals are just arrays we can index into:
#define last(x) std::printf("%c", #x[sizeof(#x) - 2]);
You want
#define last(x) printf("%c", #x[sizeof(#x)-2]);
Demo: https://ideone.com/rp0w8k
(sizeof
gives you the number of bytes in the string literal formed by stringizing the macro argument, back one to get the terminating zero, back another one to get to the last character.)
I really hope this is for interest and you're not planning to use this in real code though.