Reputation: 11
I'm trying to create a unique static variable for each function pointer and I need to use a function pointer because I plan on using them inside of a struct.
I tried creating a function pointer to a function with a static variable but it's the same variable in both of them.
#include <stdio.h>
void foo()
{
static int test = 10;
test++;
printf("%d\n", test);
}
void (*bar)() = foo;
int main()
{
foo();
bar();
return 0;
}
I expected this to give me 11 and 11 but I get 11 and 12 so it must increment the same variable twice.
Upvotes: 1
Views: 556
Reputation: 23342
This is not something a function pointer can do.
Instead of function pointers, you probably want some kind of object-orientation so you can have several objects each with its own private test
field, but sharing the same code.
For this, you need to go to C++ instead of plain C.
(If for some reason this is not available to you and you have to do your stuff in C, there's no real way around giving the function an extra context pointer as a parameter. Or, if you need only finitely many instances of the function, write it several times. They can share a helper function that does the real stuff, but each instance needs to declare their own memory for the helper function to operate on).
Upvotes: 1