Calling functions through arrays in C?

I am in the middle of writing a program that has a function that performs another function:

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

However, it might be more efficient to just have something like:

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

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

+4
source share
3 answers

This is similar to where function pointers will be useful

 typedef void (*puzzlePointer)(); puzzlePointer puzzles[] = { puzzle1, puzzle2, puzzle3 }; void executePuzzle(int input) { if (input >= 0 && input < 2) { puzzles[input](); } } 
+9
source
0
source

When the cases of the switch are contiguous, as in your executePuzzle function, it is actually likely that the compiler internally uses function pointers (via the jump table) to implement the switch .

0
source

Source: https://habr.com/ru/post/1394881/


All Articles