Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling functions through arrays in C?

Tags:

arrays

c

function

I am in the middle of writing a program which has a function which runs another function:

int executePuzzle(int input) {
    switch (input) {
        case 1: puzzle1();break;
        case 2: puzzle2();break;
        default:break;
    }
}

However it may be more efficient to simply have something like:

int puzzle[2] = {puzzle1(),puzzle2()};

Then call puzzle0; I was wondering how this would be done.

like image 935
user1150512 Avatar asked Jan 18 '23 13:01

user1150512


1 Answers

It sounds like a place where function pointers would be useful

typedef void (*puzzlePointer)();
puzzlePointer puzzles[] = { puzzle1, puzzle2, puzzle3 };

void executePuzzle(int input) {
  if (input >= 0 && input < 2) {
    puzzles[input]();
  }
}
like image 59
JaredPar Avatar answered Jan 28 '23 03:01

JaredPar