I have a function that takes a pointer to a function as a parameter. This function get's called within a for loop due to the similar nature of the names of the function pointer I use a macro to expand the name into the function. IT looks something like this:
void fill(int, int(*funcbase)(int));
int funcbase0(int);
int funcbase1(int);
int funcbase2(int);
int funcbase3(int);
/// all the way through funcbase31
#define FILL_(num) fill(num, funcbase##num)
#define FILL(num) FILL_(num)
for(int i = 0; i < 32; i++)
FILL(i);
I would like this to call fill for 0,1,2,... and funcbase0, funcbase1, funcbase2,... , but it calls fill with the second parameter of "funcbasei" It does not expand i every time.
Is what I'm trying to do possible? What compiler would I need to try? (I'm using gcc 4.9.3)
What you are trying to do is not possible with a macro because macros are expanded at compile time, well before the runtime and loops start running.
However, you can easily do this with a for
loop on an array of function pointers:
typedef int(*funcbase_t)(int);
funcbase_t fbases[] = {
funcbase0, funcbase1, funcbase2, funcbase3, ...
};
Now you can run your loop on fbase
array:
for(int i = 0; i < 32; i++)
fbases[i](i);