Want to concatenate two tokens and convert the result to string using macros and token-pasting and stringizing operators only.
#include <stdio.h>
#define concat_(s1, s2) s1##s2
#define concat(s1, s2) concat_(s1, s2)
#define firstname stack
#define lastname overflow
int main()
{
printf("%s\n", concat(firstname, lastname));
return 0;
}
but the above throws undeclared error as below
error: ‘stackoverflow’ undeclared (first use in this function)
tried having # to stringize s1##s2
#define concat_(s1, s2) #s1##s2 \\ error: pasting ""stack"" and "overflow" does not give a valid preprocessing token
If you want to concatenate and then stringize, you need to concatenate first, and then stringize:
The problem with just adding a
#to theconcat_macro is that it will try to stringize before the concat.Of course, with strings, there's no actual need to concatenate them with the preprocessor -- the compiler will automatically combine two strings literals with nothing between them except whitespace into one:
This also avoids problems if the things you want to concatenate aren't single tokens and/or don't become a single token, both of which cause undefined behavior.