简体   繁体   中英

Do I have to specify a '*' before function pointer?

When I'm passing function as parameter to other functions in c++ , do I have to specify it as

void callOtherFunctions(void f());

or

void callOtherFunctions(void (*f)());

I have no idea what happens under the hood , so I tried running both versions with a simple program as below , replacing the necessary part for 2nd run.

#include <iostream>
using namespace std;

void printHello();
void callOtherFunctions(void f());

int main() {

    callOtherFunctions(printHello);
    return 0;
}
void printHello(){
    std::cout<<"\n Hello World";
}
void callOtherFunctions(void f()){
    for (int i=0;i<5;++i){
        f();
    }
} 

and to my surprise , both execute with same output and no warnings. So which is the preferred way , or correct way ( in case I'm doing something wrong ). And what actually happens in each case , when I pass pointer - does it executes address function there and when I pass function - does it copies down whole function there? or something else?

Here is Ideone Link

void callOtherFunctions(void f());

and

void callOtherFunctions(void (*f)());

are identical. Quoting N1570,

§6.7.6.3/8 A declaration of a parameter as "function returning type " shall be adjusted to "pointer to function returning type ", as in 6.3.2.1.

I would prefer the function pointer syntax because more people would be familiar with it and it's explicit what you mean. To answer your second question, a conversion also happens in certain cases (informally known as "decay"):

§6.3.2.1/4 A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator, 65) or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type ".

Function parameter declarations are somewhat unusual; the compiler will adjust some of the declared types. This is one of them: function parameters of function type are adjusted to the corresponding pointer type.

Other common adjustments to function parameters are array to pointer type, and removing top-level const :

int foo(int a[5]);    // a is a pointer
int foo(const int a); // foo() can be called with a non-const int argument.

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