1

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)?

6
  • 7
    Nope, just two pointers to the same function. C has no concept of "instance of a function". Commented Dec 25, 2014 at 21:29
  • 1
    "I want multiple instances of that function". Why? What are you hoping to achieve with this? Commented Dec 25, 2014 at 21:33
  • @Paul OP explained why: Because they want two separate copies of the static variables declared inside the function. Commented Dec 25, 2014 at 21:49
  • Yes, I was hoping for an explanation of why they wanted that, as there's probably a different way of achieving the real purpose Commented Dec 25, 2014 at 21:55
  • 2
    Create structure holding everything you need to handle single button (move static variable into it). Create many instances of that structure (button1_ctx, button2_ctx). Pass the structure to button handler as parameter. That is. Commented Dec 25, 2014 at 22:02

2 Answers 2

5

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]);
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

2

No, you have two pointers to the same function.

1 Comment

@LasseKaragiannis See alexander's comment above. He has the right idea. A C function with static variable in its scope is effectively a singleton pattern instance. If you want object instance behavior, you must implement it yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.