Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can this function pointer not point to a function?

Tags:

c++

Why is the pointer function *pFcn not pointing to an address? It points to Add, which isn't &Add. nor does it return an address. Why is that?

int Add(int nX, int nY)
{
    return nX + nY;
}

int main()
{
    // Create a function pointer and make it point to the Add function
    int (*pFcn)(int, int) = Add;
    cout << pFcn(5, 3) << endl; // add 5 + 3

    return 0;
}
like image 448
EEstud Avatar asked Dec 16 '25 22:12

EEstud


1 Answers

If foo is a function, then (except in some specific cases*) both foo and &foo express a pointer to the function: Functions immediately decay to pointers to themselves, so foo(x), (*foo)(x) and (**foo)(x) are all the same.


When given a choice, prefer passing functions by reference rather than by value, though:

template <typename R, typename ...Args> R invoke(R (*f)(Args...), Args... args)
{
    return f(args...);

    // bad: "&f" is not useful
}
invoke_p(add, 1, 2);

template <typename R, typename ...Args> R invoke_r(R (&f)(Args...), Args... args)
{
    return f(args...);

    // good: "&f" is the expected function pointer
}
invoke_r(add, 1, 2);

*) For example, sizeof(foo) and sizeof(&foo) are not the same; the former isn't legal.

like image 104
Kerrek SB Avatar answered Dec 19 '25 14:12

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!