C preprocessor macro specialisation based on an argument

Viewed 14917

Is it possible to have one macro expanded differently for one specific argument value and differently for all other arguments?

Say I define a current user:

#define CURRENT_USER john_smith

What I want to be able to do is to have a macro that will be expanded differently if user passed matches CURRENT_USER. Mind you that I don't know all possible user a priori. The most basic case:

#define IS_CURRENT_USER(user)                   \
    /* this is not valid preprocessor macro */  \
    #if user == CURRENT_USER                    \
        1                                       \
    #else                                       \
        0                                       \
    #endif                                      

With macro like that every other macro relying on the username could be done following way:

#define SOME_USER_SPECIFIC_MACRO(user) SOME_USER_SPECIFIC_MACRO_SWITCH_1(IS_CURRENT_USER(user))

#define SOME_USER_SPECIFIC_MACRO_SWITCH_1(switch)   SOME_USER_SPECIFIC_MACRO_SWITCH_2(switch) // expand switch ...
#define SOME_USER_SPECIFIC_MACRO_SWITCH_2(switch)   SOME_USER_SPECIFIC_MACRO_##switch         // ... and select specific case

#define SOME_USER_SPECIFIC_MACRO_0  ... // not current user
#define SOME_USER_SPECIFIC_MACRO_1  ... // current user

Is this possible?

EDIT: Let me clarify. Say each programmer defines different CURRENT_USER in their config header. I want user specific macros to exand to something meaningful if and only if their user argument matches CURRENT_USER. As I would like those macros to contain _pragmas it can't be runtime check (as proposed in some anwsers below).

EDIT: Again, clarification. Say there's macro to disable optimisation of some sections of code:

#define TURN_OPTIMISATION_OFF __pragma optimize("", off)

Some programmers want to turn optimisation off for different sections of code but not all at one time. What I'd like is to have a macro:

#define TURN_OPTIMISATION_OFF(user) /* magic */

That will match user argument against CURRENT_USER macro, taken from per-programmer config file. If the user matches macro is expanded into pragma. If not, to nothing.

7 Answers
Related