Lasse Karagiannis
Lasse Karagiannis

Reputation: 481

multiple instance of same function in C

I am using C for the Arduino controller and I have a function that contains a static variable inside

int buttonReallyPressed(int i);

I want multiple instances of that function so I have done this:

typedef int (*ButtonDebounceFunction) ( int arg1);
ButtonDebounceFunction Button1Pressed = buttonReallyPressed;
ButtonDebounceFunction Button2Pressed = buttonReallyPressed;

Have I received two separate instances of the function int buttonReallyPressed(int i)?

Upvotes: 1

Views: 3953

Answers (2)

alexander
alexander

Reputation: 2753

When you create pointer to function, you don't create another instance of static variable in the function.

Workaround is: create structure holding everything you need to handle single button (move static variable into it). Create array of instances of the structure. Pass the structure to button handler as parameter.

struct button_state {
    int pressed; // or whatever
}

struct button_state button[3];

int buttonReallyPressed(struct button_state *state);

void button_isr(...)
{
    ...
    buttonReallyPressed(&button[id]);
    ...
}

Upvotes: 5

Carl Norum
Carl Norum

Reputation: 225252

No, you have two pointers to the same function.

Upvotes: 2

Related Questions