[英]C - Is there a way to call a function pointer if it's not null without repeating the function pointer?
拿這個代碼
int main() {
void (*func)(int val) = NULL;
if (func) { // check if NULL
func(0); // call it
}
}
有沒有辦法調用函數指針func
而不必寫func
兩次?
就像是
func? (0);
你可以寫一個宏:
#define CALL_FUNC(func, param) \
do { \
if (func) func(param); \
} while (0)
並使用它:
int main() {
void (*func)(int val) = NULL;
CALL_FUNC(func, 0);
}
編輯:我不推薦它,我在我的項目中使用了一段時間。 一段時間后我實際上放棄了它,它增加了一點無用的復雜性。
我終於回到了您當前的代碼,但格式為 1 行:
int main() {
void (*func)(int val) = NULL;
if (func) func(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.