This is a rather simple question that is making me a bit curious. Consider the following code snippet:
#include <iostream>
int three()
{
return 3;
}
void foo(int func(void))
{
std::cout << func() << std::endl;
}
void bar(int (*func)(void))
{
std::cout << func() << std::endl;
}
int main()
{
foo(three);
bar(three);
return 0;
}
// output:
// 3
// 3
As you can see, we have two functions that take another function as their only argument. However, the function prototypes for them differ. Mainly, we have void foo(int func(void)) and void bar(int (*func)(void)). At first glance, it looks like foo is taking the function itself, and bar is taking a pointer to a function.
However, they both produce the exact same results, and have the exact same body, and are called in exactly the same manner.
My question is, is there an actually hidden difference between foo and bar? Is this simply an optional syntax in C++? Is one of the two cases considered "bad style" in C++?
If my compiler is a contributing factor, I'm using Visual Studio 2010.
There is no difference: the types of foo and bar are the same: int(int(*)()).
There is no such thing as a function-type parameter: when a parameter appears with the function type syntax (like int func(void)), it is transformed into the corresponding pointer-to-function type (like int (*func)(void)).
The transformation is similar to how a parameter declared with array syntax (e.g. int a[]) is transformed into the corresponding pointer type (int* a).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With