Search code examples
cgeneric-programming

C _Generic error - expected expression before '_Bool'


I am learning about C _Generic. Here's the question: Why I cannot compile the code below successfully? It will only issue the error as the title.

#include <stdio.h>
#define EVALUATE(X) _Generic((X), _Bool : "boolean", default : "not boolean")

int main(void)
{
    printf("%s\n", EVALUATE(5));

    return 0;
}

Solution

  • _Generic is not supported in gcc until 4.9.0. _Bool is supported in your current compiler, but since the compiler thinks that _Generic is a regular implicit function, it pushes out a warning about the odd parameter.

    GCC 4.7.1

    [9:25am][wlynch@apple /tmp] /opt/gcc/4.7.1/bin/gcc -std=c11 foo.c
    foo.c: In function ‘main’:
    foo.c:7:5: warning: implicit declaration of function ‘_Generic’ [-Wimplicit-function-declaration]
    foo.c:7:20: error: expected expression before ‘_Bool’
    

    GCC 4.8.2

    [9:26am][wlynch@apple /tmp] /opt/gcc/4.8.2/bin/gcc -std=c11 foo.c
    foo.c: In function ‘main’:
    foo.c:7:5: warning: implicit declaration of function ‘_Generic’ [-Wimplicit-function-declaration]
         printf("%s\n", EVALUATE(5));
         ^
    foo.c:3:35: error: expected expression before ‘_Bool’
     #define EVALUATE(X) _Generic((X), _Bool : "boolean", default : "not boolean")
                                       ^
    foo.c:7:20: note: in expansion of macro ‘EVALUATE’
         printf("%s\n", EVALUATE(5));
                        ^
    

    GCC 4.9.0

    [9:26am][wlynch@apple /tmp] /opt/gcc/4.9.0/bin/gcc -std=c11 foo.c
    [9:27am][wlynch@apple /tmp] ./a.out 
    not boolean