简体   繁体   中英

How can I implement a function lookup table in C?

Say I had a program where the user could select a number between 0-10. Each number would then correspond to the calling of a certain function. In Python, I know I could just create an array of function names, index into it with the selected option, and then call the function. How would I implement this in C? Or is it even possible?

Here is an example how to do it. Please note that all functions must have the same signature, but of course you can change that from my funptr type to for example a function that has void return or takes a char and not two int s.

// Declare the type of function pointers.
// Here a function that takes two ints and returns an int.
typedef int (*funptr)(int, int);

// These are the two functions that shall be callable.
int f1(int a, int b) { return a + b; }
int f2(int a, int b) { return a - b; }

// The array with all the functions.
funptr functions[] = {
    f1,
    f2,
};

// The caller.
int call(int i, int a, int b)
{
    return functions[i](a, b);
}

The only problem that I can see in the solution from above is that there is no check for the array index (you may get some tricky problems). To make the code more robust, you can add a check for the index (boundaries), like

  • add one if statement inside of function "call" where you check the parameter i (not to be bigger than the maximum value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM