簡體   English   中英

如何在 C 中實現 function 查找表?

[英]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);
}

我在上面的解決方案中看到的唯一問題是沒有檢查數組索引(您可能會遇到一些棘手的問題)。 為了使代碼更健壯,您可以添加對索引(邊界)的檢查,例如

  • 在 function "call" 中添加一個 if 語句,在其中檢查參數 i(不大於最大值)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM