Search code examples
c++pointersc++11dereference

What's the difference between function with dereference and without dereference


What's the difference between f1, (*f1), f2, (*f2) ? and what's the difference between (function) and (&function) ?

#include <iostream>
using namespace std;

void function (char *s) {
    cout << s << endl;
}

int main () {
    void (*f1) (char*) = &function;
    void (*f2) (char*) = function;

    f1 ("f1 function without dereference.");
    (*f1) ("f1 function with dereference.");
    f2 ("f2 function without dereference.");
    (*f2) ("f2 function with dereference.");
    return 0;
}

Solution

  • What's the difference between f1, (*f1), f2, (*f2) ?

    f1 and f2 are function pointers. (*f1) and (*f2) are references to functions. What's the difference between function pointers and function references? Extremely little, as they are both callable with the exact same syntax. However, see this question for a more in-depth explanation of function references.

    and what's the difference between (function) and (&function) ?

    function is a function. &function is a pointer to a function. One extremely minor difference here relates to the fact that you can bind a function reference to a function, but not to a function pointer.

    void (&fref1)(char*) = function; // compiles
    void (&fref2)(char*) = &function; // does not compile
    

    Again, see the linked question for possible reasons you might use a function reference (there aren't many).