Marko Gulin
Marko Gulin

Reputation: 563

Macro conditional statements in C

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.

Upvotes: 8

Views: 21330

Answers (1)

alk
alk

Reputation: 70893

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.

Upvotes: 11

Related Questions