i wonder what is the difference between these 2 functions( fun
and fun2
) I know that fun2
is function pointer but what with fun
? Is that the same because there is also passing by pointer which is function name ?
#include <iostream>
void print()
{
std::cout << "print()" << std::endl;
}
void fun(void cast())
{
cast();
}
void fun2(void(*cast)())
{
cast();
}
int main(){
fun(print);
fun2(print);
}
Is that the same because there is also passing by pointer which is function name ?
Yes. This is inherited from C. It's solely for convenience. Both fun and fun2 are taking in a pointer of type "void ()".
This convenience is allowed to exist because when you invoke the function with parenthesis, there is NO AMBIGUITY. You must be calling a function if you have a parenthesized argument list.
If you disable compiler errors, the following code will also work:
fun4(int* hello) {
hello(); // treat hello as a function pointer because of the ()
}
fun4(&print);
http://c-faq.com/~scs/cclass/int/sx10a.html
Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?
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