Mark Jeronimus
Mark Jeronimus

Reputation: 9541

Difference between two ways of passing function as parameter

These two ways of defining a function accepting another function seem to work identically (as in, the body is the same for both functions). I found the first one by fiddling, and then found the second one on several websites.

void foo(int bar())
void foo(int (*bar)())

Example body:

{
    for (int i = 0; i < 10; i++)
      cout << bar() << ' ';
}

What's the difference? Is one preferred over the other? Is it compiler or C++ version dependent?

Upvotes: 0

Views: 73

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

For me a preferable way is

void foo( int bar( void ) );

because a function declaration as a parameter looks more clear.

It is similar to writing whether

void f( int a[] );

or

void f( int * );

The first declaration gives the reader of the code the idea that the function accepts an array instead of a pointer to a single object.

For example

int main( int argc, char * argv[] )

looks more clear then

int main( int argc, char ** argv )

In fact there is no difference because the compiler implicitly adjusts a parameter of a function type to pointer to the function type.

From the C++ 17 Standard (11.3.5 Functions)

5 The type of a function is determined using the following rules. The type of each parameter (including function parameter packs) is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”....

Upvotes: 1

Quentin
Quentin

Reputation: 63154

They are identical, as per function parameters declaration rules.

The type of each function parameter in the parameter list is determined according to the following rules:
...
3) If the type is a function type F, it is replaced by the type "pointer to F"
...

Upvotes: 4

Related Questions