简体   繁体   中英

How to get value macro in C?

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);
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM