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

前端 未结 7 2242
梦谈多话
梦谈多话 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条回答
  •  抹茶落季
    2020-11-22 04:46

    This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

    typedef void (*functiontype)();
    

    Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

    void dosomething() { }
    
    functiontype func = &dosomething;
    func();
    

    For a function that returns an int and takes a char you would do

    typedef int (*functiontype2)(char);
    

    and to use it

    int dosomethingwithchar(char a) { return 1; }
    
    functiontype2 func2 = &dosomethingwithchar
    int result = func2('a');
    

    There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

    boost::function functiontype2;
    

    is so much nicer than the above.

提交回复
热议问题