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

Viewed 324

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);
}
3 Answers

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.

*callback() invokes operator() on callback then dereferences (*) the result of that function call.

(*callback)() dereferences callback and then invokes operator() on the result of that dereference.

Two very different things.

*callback just dereferences the pointer but does nothing with the result. Semantically valid but doesn't do anything in this context.

See also C++ Operator Precedence

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

*callback() does not work because the function returns void. A void expression cannot be an operand.

*callback "works" in the sense that it is a well-formed expression. It is however not a function call expression, so you haven't called any function by doing this.

(*callback)() works because the indirection through the function pointer results in a function reference, which you call by using the empty parameter list. callback() would also work because function pointers can be called directly, in which case the indirection through the pointer is implicit.

Related