cmacoscompiler-errorsswitch-statementcomma-operator

Why does this macro with a comma operator fail to compile in a switch statement?


#include <stdio.h>

#define PRINT(x) (printf("%d\n", x), x)

int main() {

    int a = 1;

    switch (a) {
        case PRINT(1): puts("Case 1"); break;
        case PRINT(2): puts("Case 2"); break;
        default: puts("Default");
    }
}

After building the code, I'm getting the error as:

error: case label does not reduce to an integer constant

Why does the PRINT macro fail in the switch statement, and how can I fix it?


Solution

  • case needs an integer constant expression, hence the self-explaining compiler error. (clang gives an even clearer one: "error: expression is not an integer constant expression")

    printf("%d\n", x), x is not and integer constant expression - it contains variable evaluations and even a function call. You will have to move the printing outside the case :.