Home > database >  Is it possible to change the behavior of a #define at compile time depending on a parameter in C?
Is it possible to change the behavior of a #define at compile time depending on a parameter in C?

Time:08-24

Having this code:

// Called when x is "a"
#define do(x) doA()

// Called when x is "b"
#define do(x) doB()

Is it possible to make the preprocessor interpret do("a") as doA() and do("b") as doB() and maybe some other doUndefined() if unknown x provided? To clarify: I want to map x parameter to arbitrary code or function call, not just call do{uppercase_x}(). It must be done at compile time. And the x parameter must be a string.

Thanks!

CodePudding user response:

It can't be done for arguments with spaces. Without spaces, you can define macros for each allowed value. Those macros, in turn, can expand to your desired macros, insulating the argument names from the final macro names. For example:

#define do(x) do_##x

#define do_a doA
#define do_b doB

Then do(a) would expand to doA and do(b) would expand to doB.

Update: As paddy mentioned, do is a reserved keyword in C, so you should pick a different name for your macro.

  • Related