Search code examples
cgcclisp

Is there a way to execute arbitrary code in C preprocessor?


Consider this program:

#define MACRO                                   \
    srand(time(NULL));                          \
    if (rand() % 2)                             \
        printf("A");                            \
    else                                        \
        printf("B");

int main() {
    MACRO;
}

It is the equivalent of the following macro-expanded program:

int main() {
    srand(time(NULL));
    if (rand() % 2)
        printf("A");
    else
        printf("B");
}

Obviously, the if statement is executed in runtime and not in macro-expansion phase. If the if statement was executed in compile time and if there was syntax quoting (as in Lisp), we could get programs A and A' with (almost) equal probability. Where A:

int main() {
    printf("A");
}

and A':

int main() {
    printf("B");
}

Is there a way to make GCC emit A or A' with regard to a condition evaluated in compile time?


Solution

  • Is there a way to execute arbitrary code in C preprocessor?

    No, and this was an intentional design decision by the authors of the original (1989) C standard. They were familiar with much more powerful macro systems (e.g. from Lisp, which does allow for arbitrary computation at compile time) and they thought those made it too hard to understand what an unfamiliar program means.

    It is not clear to me why you want to make a random choice at compile time. If you explain your larger goals we may be able to be more helpful.