dilan_s
dilan_s

Reputation: 149

#define/macro to return a function pointer to a function given in the same file

Say I have code

void 1funct() {
(...)
}

void 2funct() {
(...)
}
etc., to 

void nfunct() {
(...)
}

Is it possible to return the function pointer to the correct function given an n by

#define RET_FUNC_POINTER(n) (&nfunct); ?

Upvotes: 1

Views: 766

Answers (2)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

Yes — macros can concatenate source code characters into a single token using ##:

#define RET_FUNC_POINTER(n) (&n ## funct);

(Tokens are the invisible "building blocks" of your source code, discrete units of text that the parser generates from your code while trying to understand your program. They are roughly analogous to "words" in English, but they do not need to be separated by spaces in C++ unless omitting a space would just produce a single token: e.g. int main vs intmain, but int * vs int*. With ## we can take the two would-be tokens int and main, and use the preprocessor to force them into intmain instead. Just, one of your arguments is a "variable" to the macro. Notice that you don't need to join & and the n ## funct part, as the & is already a separate token, and should remain that way.)

However, you may wish to consider a nice array of pointers instead.

If the n is known statically at compile-time (which it must be for your macro to work) then you don't really gain anything over just writing &1funct, &2funct etc other than obfuscating your code (which isn't a gain).

Also note that your function names cannot start with digits; you'll have to choose a different naming scheme.

Upvotes: 2

Lundin
Lundin

Reputation: 213989

Not sure why you want to do this (instead of just using a const array), but it's quite easy to do with a macro:

#define RET_FUNC_POINTER(n) (n##funct)

Upvotes: 1

Related Questions