EEstud
EEstud

Reputation: 309

How can this function pointer not point to a function?

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;
}

Upvotes: 3

Views: 219

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477710

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.

Upvotes: 4

mujjiga
mujjiga

Reputation: 16926

printf("%p\t%p",pFcn,Add)

pFcn gives the address of the function which it is pointing which in this case is the address of funciton Add. pFcn(1,2) calls the function.

Upvotes: 0

Related Questions