Question about passing a function to a function's argument

I learned how to pass a (callback) function to a function's argument like so:

1
2
3
void Update(void (callback())) {
    (*callback)(); // No Error
}


But I also noticed that there's probably some extra parenthesis in the argument I can remove like this:

1
2
3
void Update(void callback()) {
    (*callback)(); // No Error
}


...and my code still works.

Yet when I try removing it from where the call back function is actually called, I get a compiler error:

1
2
3
void Update(void callback()) {
    *callback(); // Compiler Error: void value not ignored as it ought to be
}


Why? I'm trying to understand why parenthesis were added in the first place. I learned this method at a post from this very forum: http://www.cplusplus.com/forum/beginner/6596/

Thank you in advance!
Last edited on
Two words: operator precedence

Function call () is in group 2
Dereference * is in group 3

http://en.cppreference.com/w/cpp/language/operator_precedence

Using parentheses around *callback will cause that to be computed first before the function call can use the result of what happened in the parentheses to its left. Otherwise, you are calling the callback function and then trying to dereference void. Which is not allowed in C++ because there is nothing to dereference in a void.
Last edited on
Thanks for the answer and the link @kevinkjt2000, just wanted to understand what I was doing there. Now I know.
Note that you don't need to dereference a function pointer. Dereferencing a function pointer gives you the same function pointer.

1
2
3
4
5
using callback_type = void();

void Update(callback_type cb) {
    cb();
}


Although a more flexible approach might be:
1
2
3
4
template <typename func_type>
void Update(func_type cb) {
    cb();
}

which opens things up for callback functions with return types other than void, lambdas and objects which overload operator().
Last edited on
closed account (48T7M4Gy)
For a well rounded answer stack rarely fails

http://stackoverflow.com/questions/13472443/calling-a-function-through-a-function-pointer-dereference-the-pointer-or-not

Of course for those with an interest in qt creator and the like, callbacks are very down market as they are supplanted with signals and slots
Last edited on
Didn't notice the last answers, thanks @cure @kemort.

1
2
3
4
template <typename func_type>
void Update(func_type cb) {
    cb();
}


...this definitely looks cleaner.
Topic archived. No new replies allowed.