最近我在編程(用 C 語言),我意識到如果我可以撰寫自己的回圈函式,我的代碼會更簡單。所以我需要在不同的時間運行一段代碼(代碼段在整個程式中各不相同),但我不知道如何在我的函式中將一段代碼作為引數。
例如,以 for(){"X"} 回圈為例,其輸出可能因“X”而異,因此我們可以以某種方式將“X”作為函式中的引數。
雖然我在沒有定義新函式的情況下在代碼中解決了這個問題,但它導致了一個更普遍的問題,我在網上找不到答案:有沒有辦法在函式中使用一段可變代碼?(以與 for() 相同的方式)
編輯:這是我在網上找到的類似問題。然而,我的問題比這個問題更籠統。
uj5u.com熱心網友回復:
您可以將代碼放入函式中并將函式(作為指標)傳遞給其他函式(或在回圈中使用它),如下所示:
#include<stdio.h>
static int add(int a, int b)
{
return a b;
}
static int multiply(int a, int b)
{
return a * b;
}
/* The third argument to g, f, is a pointer to a function that takes two int
parameters and returns an int.
*/
static void g(int a, int b, int (*f)(int a, int b), const char *name)
{
// This uses the pointer f to call the function.
printf("The %s of %d and %d is %d.\n", name, a, b, f(a, b));
}
int main(void)
{
// These pass the function add or multiply to g.
g(3, 4, add, "sum");
g(3, 4, multiply, "product");
}
C 在這方面沒有很大的靈活性。所涉及的函式應該大多具有相同的簽名(采用相同型別的引數并具有相同的回傳型別)。使用可變引數串列或強制轉換為不同的函式型別可以提供一些靈活性,但是,當使用指向函式的指標時,您通常應該尋求統一的簽名。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363032.html
