Search code examples
cswitch-statementc-preprocessorconditional-compilation

C compiler directives with switch/case statements?


What do I do with this switch-case statement in C?

#if defined MY_CONST && define RUN_TEST
    case TX_ERROR:
        //code here
        break;
    case RX_ERROR:
        //other code here
        break;
#endif

I'm coding in an existing project, and I see the above lines in an included header file (in the file I'm working on). No mention of a "switch" anywhere else in the header file!

I've never seen this before! How can these be case switches without the switching? Since this must be possible, how can I use these cases in a switch statement in my main file?

EDIT: I can't post the actual file (code base under licence?), but here's a stripped version:

#if defined _CONFIG
    #define MY_CONST
    #define MY_INIT
    #define RUN_TEST

    static void fnInit(void);
    static void fnGo(void);
#endif

#if defined MY_CONST && define RUN_TEST
    case TX_ERROR:
        //code here
        break;
    case RX_ERROR:
        //other code here
        break;
#endif

#if defined MY_INIT && defined MY_CONST
static void fnInit(void)
{
    //code
}

static void fnGo(void)
{
    //code
}
#endif

Solution

  • Make sure that MY_CONST is never defined!

    If what you quote is accurate, then you'd have to include the header in the scope of a switch statement for the result with MY_CONST defined to make any sense. If it is not embedded in a macro, then it is basically an accident waiting to happen.


    With the revised content, make sure that you never have both MY_CONST and RUN_TEST defined. There is no way for the header to be used sanely if they are -- not even if you are using GCC and have nested functions enabled.

    Fundamentally, that fragment is a bug in the header.