[英]How can I implement a function lookup table in C?
假設我有一個程序,用戶可以在其中 select 一個介於 0-10 之間的數字。 然后每個數字將對應於某個 function 的調用。 在 Python 中,我知道我可以創建一個 function 名稱的數組,使用所選選項對其進行索引,然后調用 function。 我將如何在 C 中實現這一點? 或者甚至有可能嗎?
這是一個如何做到這一點的例子。 請注意,所有函數必須具有相同的簽名,但當然您可以將其從我的funptr
類型更改為例如具有void
return 或采用char
而不是兩個int
的 function 。
// 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);
}
我在上面的解決方案中看到的唯一問題是沒有檢查數組索引(您可能會遇到一些棘手的問題)。 為了使代碼更健壯,您可以添加對索引(邊界)的檢查,例如
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.