0

I'm a beginner in C++ and I have a problem understanding pointers to functions:

main()
{
    double pam(int);
    double (*pf)(int);
    pf = pam;            
    double x = pam(4);    
    double y = (*pf)(5); 
    double y = pf(5);
} 

How can (*pf)() and pf() be the same, where pf is a pointer to the function?

What is the difference between other pointers and a pointer to the function??

Aayush Neupane
  • 1,066
  • 1
  • 12
  • 29
  • 6
    you're going to find this question and answers highly enlightening: [How do function pointers work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – WhozCraig Oct 23 '19 at 23:59
  • Possible duplicate of [How do function pointers in C work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – slfan Oct 24 '19 at 06:01
  • Fun note: try adding some more `*`. – rubenvb Oct 24 '19 at 10:14

1 Answers1

5

how can *pf() and pf() be the same where pf is a pointer to the function?

They aren't the same (because of operator precedence). In case you meant (*pf)() and pf() are effectively the same, then that's because the rules of the language say so. Specifically, the rules say:

[expr.call]

A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of initializer-clauses which constitute the arguments to the function. The postfix expression shall have function type or function pointer type. For a call to a non-member function or to a static member function, the postfix expression shall either be an lvalue that refers to a function (in which case the function-to-pointer standard conversion ([conv.func]) is suppressed on the postfix expression), or have function pointer type.

In case of (*pf)(), the expression (*pf) is an lvalue that refers to a function, while in the case of pf(), the expression pf has a function pointer type. In both cases the function pointed by pf is called.

What is the difference between other pointers and a pointer to the function??

The primary difference is that function pointers point to functions, and pointers to objects point to objects.

eerorika
  • 232,697
  • 12
  • 197
  • 326