callback function: difference between void(*func)(

2019-05-02 15:08发布

So Lets say I have a function:

void foo (int i){
    cout << "argument is: " << i << endl;
}

And I am passing this function to:

void function1 (void(callback)(int), int arg){
    callback(arg);
}

void function2 (void(*callback)(int), int arg){
    callback(arg);
}

are these two functions identical? Is there any difference between the two?

2条回答
做个烂人
2楼-- · 2019-05-02 15:53

They are identical. Parameter having type of a function is converted to pointer to the function type.

查看更多
混吃等死
3楼-- · 2019-05-02 15:55

The rule is that in a function's parameter list, a parameter declared to have a function type is adjusted to have pointer to function type (similarly, and probably more well-known, a parameter declared to have type "array of T" is adjusted to have type "pointer to T". Redundant parentheses in declarators are allowed, but ignored.

Thus, in

void function1 (void(callback)(int), int arg);
void function2 (void (*callback)(int), int arg);
void function3 (void callback(int), int arg);

The first parameter of those three functions have exactly the same type - "pointer to function of (int) returning void".

查看更多
登录 后发表回答