Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 818
Marko Gulin Avatar asked Dec 03 '16 12:12

Marko Gulin


1 Answers

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.

like image 93
alk Avatar answered Oct 02 '22 14:10

alk