Search code examples
c++callbackoperator-precedence

why does (*callback)() work and not *callback() or *callback in c++


I'm a beginner C++ student and I thought that to really learn pointers and references I should try to make a callback function, something I take for granted in JavaScript.

But, for the life of me, I don't know why these parentheses are so important in (*callback)() and I'd love it if someone could explain it to me.

Here's some code I wrote that worked somehow:

#include<cstdio>

void function_two()
{
    printf("then this runs!");
}

void function_one(void (*callback)() = nullptr)
{
    printf("this runs first");
    if(callback != nullptr)
    {
        (*callback)();
    }
}

int main()
{
    function_one(&function_two);
}

Solution

  • In fact you can just write

    callback();
    

    If you are using the unary dereference operator * then it has a lower priority relative to the postfix function call operator. So you have to write

    (*callback)();
    

    Otherwise such a call

    *callback();
    

    is considered by the compiler as dereferncing the result of the function call.

    Bear in mind that you can even write something like the following

    (******callback)();
    

    because the resulting function designator is converted back to a function pointer.