Search code examples
cpointersfunction-pointers

Call a function using a pointer and pass it along in the parameters


Say that I have a pointer to function theFunc. theFunc takes along a pointer that points to the address where theFunc is stored . Is this possible?

Using it would look like this:

funcPtr(funcPtr);

That calls the function pointed to by funcPtr, and then passes along the address of the pointer. I do not want to use void pointers because I want to change the function pointed to by funcPtr.


Solution

  • You cannot simply typedef a function type that accepts itself as a parameter. I.e. something like this will not work:

    /* Will cause a compilation error, MyFuncType used a parameter is not yet defined: */
    typedef void(*MyFuncType)(MyFuncType);  
    

    However - you can still use a void* to achieve what you want. The typedef is using void*, but inside the function you can cast it to your function pointer type, modify it and call it.

    See here:

    typedef void(*MyFuncType)(void*);
    
    void f(void* pF)
    {
        if (pF)
        {
            MyFuncType ff = (MyFuncType)pF;
            /* Change ff here if you need. */
            /* Call it: */
            ff(0);
        }
    }
    
    int main()
    {
        f(f);
        return 0;
    }
    

    Update:
    Following the comment from @JosephSible-ReinstateMonica below, I added a 2nd solution. It does not involve a cast between data and function pointers, but it requires another typedef and a cast when calling f with itself:

    typedef void(*FuncType1)(void);
    typedef void(*MyFuncType)(FuncType1);
    
    void f(MyFuncType pF)
    {
        if (pF)
        {
            /* Change pF here if you need. */
            /* Call it: */
            pF(0);
        }
    }
    
    int main()
    {
        f((MyFuncType)f);
        return 0;
    }