6

I was demonstrating to a learning colleague how to use function pointers and how he could have an array of them. I put down the following code so that he could do indexed dispatch:

typedef void (*VoidFunction)();
VoidFunction functions[]  =
    {editProgramName,
     editProgramLength,
     editProgramCycles,
     editProgramNumberOfSets,
     editProgramEditSets,
     editProgramSave,
     editProgramCancel};
// now dispatch                    
functions[scroll.arrayFocusIndex]();

And then he asked... "How do I do it without the typedef?" To which I found after trying various things that seemed like they might work, I didn't have a clue to do. All the google hits I found always seemed to use a typedef. Is there a way to do it inline without the typedef of the function pointer?

3
  • 4
    Yes. The syntax would be: void (*functions[])() = {... Commented Dec 6, 2012 at 23:15
  • @JerryCoffin You're quick. I was going to post that. (May I still do it?) Commented Dec 6, 2012 at 23:16
  • Oh, and OP: +1 for a good question. Commented Dec 6, 2012 at 23:17

2 Answers 2

4
void (*functions[])() =
    {editProgramName,
     editProgramLength,
     editProgramCycles,
     editProgramNumberOfSets,
     editProgramEditSets,
     editProgramSave,
     editProgramCancel};
// now dispatch
functions[scroll.arrayFocusIndex]();
Sign up to request clarification or add additional context in comments.

2 Comments

Dammit, I started testing this before Jerry Coffin posted his comment. Honest.
Could have sworn that was one of the darts I threw at it, but apparently not. Seems obvious when I look at it now. Thank you so much!
3

This has worked for me:

void a()
{
}

void b()
{
}

void (*functions[2])();

int main()
{
    functions[0] = a;
    functions[1] = b;
    return 0;
}

5 Comments

@GManNickG Why delete your answer? It was good. But thanks anyway :)
Your first comment to Jerry was 3 second earlier than my answer. :) So I'm concluding you saw the question first.
@GManNickG Maybe yes. Who knows :)
Gave you both an upvote to try and even things out a little. :)
@H2CO3 - What was your answer?

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.