Is it possible to implement a macro conditional inside a macro function in C. Something like this:
#define fun(x)
#if x==0
    fun1;
#else
    fun2;
#endif
#define fun1 // do something here
#define fun2 // do something else here
In other words, preprocessor decides which macro to use based on an argument value.
fun(0) // fun1 is "preprocessed"
fun(1) // fun2 is "preprocessed"
I know that this example doesn't work, but I want to know is it possible to make it work somehow?
M.
You cannot use pre-processor conditionals inside a pre-processor directive. Background and workarounds you find for example here: How to use #if inside #define in the C preprocessor? and Is it possible for C preprocessor macros to contain preprocessor directives?
Still, you could do:
#include <stdio.h>
#define CONCAT(i) fun ## i() /* For docs on this see here:
                                https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html */
#define fun(i) CONCAT(i)
void fun1(void)
{
  puts(__FUNCTION__);
}
void fun2(void)
{
  puts(__FUNCTION__);
}
int main(void)
{
  fun(1);
  fun(2);
}
This would result in:
...
int main(void)
{
  fun1();
  fun2();
}
being passed to the compiler and print:
fun1
fun2
You could obfuscate your code even more by doing for example:
... 
#define MYZERO 1
#define MYONE 2
int main(void)
{
  fun(MYZERO);
  fun(MYONE);
}
resulting in the same code being passed to the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With