#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MY_CONTENT "123hello123"
#define SEARCH(TARGET, CONTENT) \
({int ret = 0; do { \
if (strstr(CONTENT, TARGET)) \
ret = 1; \
else \
ret = 0; \
} while (0); ret;})
int main()
{
#if (SEARCH("hello", MY_CONTENT))
printf("I found hello\n");
#else
printf("I am so sad\n");
#endif
}
In this code, I'd like to use the macro function "SEARCH" to control compile with different code.
But when I compile the code, it prompt me this error: gg.c:18:32: error: token "{" is not valid in preprocessor expressions
Taking your original code, your #if condition becomes equivalent to #if (( {int ret = 0; do { if (strstr(CONTENT, TARGET)) ret = 1; else ret = 0; } while (0); ret;} )) .
I'm pretty sure you can't have curly braces in an #if condition...
In any case, even if you could, the preprocessor wouldn't know what the heck you're trying to do. It doesn't really know anything about the language -- so #if <some code here> is meaningless.
C++ provides meta-flow-control through templates and generalized constant expressions. The use of macros to mimic such behavior is generally frowned upon (and rightly so).