Home > Software design >  How to get value macro in C?
How to get value macro in C?

Time:11-04

I'm having trouble with macros in C. Is there any way to call and get the value of a parameter in macro to call a function?

The example code below generates an error:

#define order(i) fruits_i##_banana()

void fruits_1_banana()
{
    printf("Order banana\n");
}

int main()
{
   int a = 1;
   order(a);
}

CodePudding user response:

You need to use ## before and after i.

#define order( i ) fruits_##i##_banana()

void fruits_1_banana()
{
    printf("Order banana\n");
}

int main()
{
   order(1);
}

Note that you cannot pass a to order because macro expansion doesn't take the value of a variable, it just uses the variable name as it is.

References: https://docs.microsoft.com/en-us/cpp/preprocessor/token-pasting-operator-hash-hash?view=msvc-160

Instead, you can use an array of function pointers:

#include <stdio.h>

static void fruits_0_banana(void)
{
    printf("Order banana 0\n");
}

static void fruits_1_banana(void)
{
    printf("Order banana 1\n");
}

static void (*order[])(void) = {
    fruits_0_banana, // Or NULL if you don't need it
    fruits_1_banana,
    // ...
};

int main(void)
{
    int a = 1;

    order[a]();
    return 0;
}
  • Related