Passing function pointers as arguments

16,348

Solution 1

Functions work kind of like arrays here. Suppose you have:

char hello[5];

You can refer to the address of this variable directly as hello - the variable name "decays" into a pointer - or as &hello, which explicitly obtains the address.

Functions are the same: if you write TestFn it decays into a function pointer. But you can also use &TestFn. The latter form might be better because it is familiar to more people.

Solution 2

Just like you pass the address of string without using the ampersand '&' sign, you don't need to use the ampersand sign to say you are passing a function pointer . You can search the book by K & R . It contains a good explaination

Share:
16,348
CuriousSid
Author by

CuriousSid

Updated on June 30, 2022

Comments

  • CuriousSid
    CuriousSid almost 2 years

    I was revisiting function pointers in C using the following simple code:

    unsigned TestFn(unsigned arg)
    {   
        return arg+7;
    }
    
    unsigned Caller(unsigned (*FuncPtr)(unsigned), unsigned arg)
    {
        return (*FuncPtr)(arg);
    }
    

    I called it using

    Caller(TestFn, 7)  //and
    Caller(&TestFn, 7)
    

    both gave the same output : 14. What's the explanation of this. I had been using the second way of calling earlier.