Given a print function:
void print(int i)
{
cout << i << endl;
}
Why are we allowed to do this in the main function :
void (*bar)(int);
bar = &print;
But not this:
void fizz(int);
fizz = print;
But when it comes to function parameters, we can pass a pointer to a function or a copy of the function:
void foo(void (*f)(int))
{
(*f)(1);
}
void test(void f(int))
{
f(1);
}
Anyone know the reason for these differences?
A function pointer can point to any function that has the same parameters and return type. In your codes above, "bar" is a pointer, and bar=&print
means let bar
point to print
. However, a function cannot =
a function.
What's good for a function pointer is that it can point to ANY function as long as the function has the same parameters and return type. This proves quite useful when a function pointer serves as a parameter of another function.
When function is used as an argument, the real thing that is passed is the ADDRESS of the function. A function cannot be passed dereferenced (ie it cannot be passed AS a function). I'm not quite clear, but it seems your implementations of foo
and test
are identical.
I would recommend reading up on std::function from c++11: http://en.cppreference.com/w/cpp/utility/functional/function
This will allow you to do more what you intend, where void(int) refers to the return type and list of arguments for your function:
void fizz( std::function<void(int)> f )
{
f(1);
}
Functions are now first class data types. You can even use function for class methods without any painful syntax. You can also make the lazy/dynamic replacement using auto for many situations. Also you can use the same setup to do interesting things like launching functions asynchronously.
auto used_to_call_fizz = fizz;
used_to_call_fizz( f );
std::async( used_to_call_fizz, f );
Every function have its own address, you can see it as an array
. The functions void fizz(int)
and void print(int i)
have different memory address, so the fizz = print;
will get an error. But you use void (*bar)(int);
, it shows a function's pointer which is used for pointing to a function. When you use bar=&print
, it will initialize the bar
pointer and then get the correct answer. By the way, you can use bar=print
, as they have the same memory address which is same as the array
. I hope this can help you.
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.