These macros are including or excluding text:
#include <stdio.h>
#define SKIP_TEXT(text)
#define JOIN_TEXT(text) text
int main(void)
{
#define S(TEXT) "a" TEXT("b") "c" TEXT("d")
printf("%s\n", S(SKIP_TEXT));
printf("%s\n", S(JOIN_TEXT));
return 0;
}
Output:
ac
abcd
Now I'm trying to do the same without defining S
for each string to evaluate, but I don't know how to replace TEXT
with SKIP_TEXT
or JOIN_TEXT
#include <stdio.h>
#define SKIP_TEXT(text)
#define JOIN_TEXT(text) text
#define S(s) S_EXEC(s)
#define S_EXEC_SKIP(s) s /* Here I want to skip text */
#define S_EXEC_JOIN(s) s /* Here I want to join text */
#define S_EXEC(s) S_EXEC_##s
int main(void)
{
printf("%s\n", S(SKIP("a" TEXT("b") "c" TEXT("d")));
printf("%s\n", S(JOIN("a" TEXT("b") "c" TEXT("d")));
return 0;
}
Is there any way to evaluate the arguments from S()
?
What you are asking is probably impossible, as it would require symbol redefinion inside a macro, instead of a simple macro expansion.
Simplest alternative would probably be:
#define TEXT SKIP_TEXT
printf("%s\n", "a" TEXT("b") "c" TEXT("d"));
#define TEXT JOIN_TEXT
printf("%s\n", "a" TEXT("b") "c" TEXT("d"));
or without SKIP_TEXT
/ JOIN_TEXT
-macros:
#define TEXT(x)
printf("%s\n", "a" TEXT("b") "c" TEXT("d"));
#define TEXT(x) x
printf("%s\n", "a" TEXT("b") "c" TEXT("d"));
#undef TEXT
is probably needed after each printf
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.