Larry The Blackbird
Larry The Blackbird

Reputation: 89

Prepocessor ## Operator and variable

Is there a way to "generate" a function name by using the operator ## and a variable value. For example:

#define FUN_I(fun, fun_id)  fun##fun_id
#define FUN(fun, fun_id)    RECV_CB_FUN_I(fun, fun_id)

int foo0(int x) {
    // do something
}
int main()
{
   int i = 0;
   FUN(foo,i)(1);
}

Macro FUN generates fooi. Is there a way to get foo0 somehow, or I have to use the actual number 0 in this case, e.g FUN(foo, 0)(1);

Cheers

Upvotes: 0

Views: 79

Answers (3)

Serge
Serge

Reputation: 12384

'c' preprocessing is a process of replacing macros with the text from their definitions. some operations like ## allow to add its argument as text into definitions. So, everything is done even before compilation starts.

As a result, in your case FUN(fun,i) will be substituted as text and form funi. The only limited way to build function names like you want is to use actual text values or other macros. Here are 2 examples which will work with pre-processing:

FUN(fun, 0)(1);

or

#define I 0
FUN(fun, I)(1);

In the last case I is a macro itself, therefore it also works. (it is always a good idea to name macro name in upper case letters).

Upvotes: 1

Meher Khiari
Meher Khiari

Reputation: 111

As stated, the macro expansion is done at compile time, so the function name wouldn't be know at run time.

It is more appropriate to use function pointers and an array to them.

Example:

typedef int (*TFoo)(int);

int foo1(int x)
{
    printf("from foo1: x = %d\n", x);
    return 0;
}

int foo2(int x)
{
    printf("from foo2: x = %d\n", x);
    return 0;
}

TFoo foos[2] = {foo1, foo2};
#define foo(i, x) foos[i](x)

That's that. Hope it helps

Upvotes: 2

rveerd
rveerd

Reputation: 4006

You have to use actual 0 (or another macro). Macro expansion is handled by the C pre-processor at compile time. It knows nothing about runtime values of variables.

Upvotes: 3

Related Questions