3

Consider the code

int add(int a, int b)
{
    return a + b;
}    

int main()
{
    std::cout << (*add)(3, 2);
}

What is the point of dereferencing the function pointer ???

I can't think of such a use case where it would give an advantage ...

Why this function call syntax exists in C++ ?

ampawd
  • 968
  • 8
  • 26
  • 3
    In the code you posted, there is no point in dereferencing. –  May 30 '18 at 19:07
  • @NeilButterworth yes, but my question is in general ... – ampawd May 30 '18 at 19:08
  • 6
    It's valid C++ because the standard allows it. It is, however, pointless, as the standard also says that dereferencing a function pointer just gives the function pointer. `(**add)(3,2)` is also valid, as is `(***********add)(3,2)`, and all are functionally equivalent. – Zinki May 30 '18 at 19:08
  • 2
    @Zinki Dereferencing the function pointer doesn't give the function pointer itself, but a reference to the function (which then decays back to a function pointer as often as necessary). – Daniel H May 30 '18 at 19:58

2 Answers2

0

I can't be sure if I am right, but here is a possible explanation: Every function in c and as well as in c++ is a potential variable. Possible declaration of function is:

int (*MyFunction)(int, double);

In this case- Variable name: MyFunction | Type: function that returns int with int, double parameters.

So, even when you declare function, you actually declare variable with a "function" type. In this case, it is make sense why can you use, in your case (*add)(3, 2) for function calling (or using a variable).

It may by more clearly for you to have a look on lambda expressions, which can make a function implementation, and then let you use it like a local function variable:

int(*MyFunction)(int, double) = [](int a, double b) -> int {
    return (int)((a + b) * 10);
};

Here we declare on function type variable, and implement a function for it with a lambda expression. Now we can use it in two forms:

MyFunction(1, 2.5); // Like a regular function
(*MyFunction)(1, 2.5); // As a function type variable

Again, it is the most sense explanation that I could think of. I don't sure if it is a right/best/fully explanation, but I hope it gave you a new perspective of functions.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
0

This syntax exists because C had it, and C++ syntax was originally based on C.

There is no difference in the code behaviour of f(args) and (*f)(args).

M.M
  • 138,810
  • 21
  • 208
  • 365