簡體   English   中英

如何在C中將函數作為參數?

[英]How to put a function as an argument in C?

我想執行函數參數中給出的函數。 讓我用一個例子來解釋。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int object() {
    printf("Hello, World!");
    return 0;
}

int run_func( int a_lambda_function() ) {
    a_lambda_function();
    return 0;
}

int main() {
    run_func( object() );
    return 0;
}

現在,我想在“run_func( int a_lambda_function() ”)的參數中運行“object()”。 當我運行它時,它返回一個錯誤。 我將如何實現全 C?

我的限制:

  1. 絕對不允許 C++

函數可以作為參數傳遞,也可以作為函數指針存儲到變量中。

與您的object函數兼容的函數指針的定義是int (*funcp)()即:指向具有未指定數量的參數並返回int的函數的指針。

在現代 C 中,不再使用具有未指定數量參數的函數,並且沒有參數的函數必須用(void)參數列表聲明。

這是修改后的版本:

#include <stdio.h>

int object(void) {
    printf("Hello, World!");
    return 0;
}

int run_func(int (*a_lambda_function)(void)) {
    return a_lambda_function();  // can also write (*a_lambda_function)()
}

int main() {
    return run_func(object);
}

暫無
暫無

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

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