How do you pass a function as a parameter in C?

前端 未结 7 2267
梦谈多话
梦谈多话 2020-11-22 04:08

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?

7条回答
  •  旧时难觅i
    2020-11-22 04:31

    Pass address of a function as parameter to another function as shown below

    #include 
    
    void print();
    void execute(void());
    
    int main()
    {
        execute(print); // sends address of print
        return 0;
    }
    
    void print()
    {
        printf("Hello!");
    }
    
    void execute(void f()) // receive address of print
    {
        f();
    }
    

    Also we can pass function as parameter using function pointer

    #include 
    
    void print();
    void execute(void (*f)());
    
    int main()
    {
        execute(&print); // sends address of print
        return 0;
    }
    
    void print()
    {
        printf("Hello!");
    }
    
    void execute(void (*f)()) // receive address of print
    {
        f();
    }
    

提交回复
热议问题