简体   繁体   中英

callback function: difference between void(*func)(int) and void(func)(int)

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?

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 ".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM