Function Index - 2 Options

I wonder what is the difference between these two functions ( fun and fun2 ). I know fun2 is a function pointer, but what about fun ? Is it the same because there is also a pointer passing, which is the name of the function?

 #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); } 
+8
c ++ function-pointers
source share
1 answer

Is it the same because there is also a pointer passing, which is the name of the function?

Yes. It inherits from C. This is for convenience only. Both fun and fun2 take a pointer of type "void ()".

This convenience is allowed to exist, because when you call a function with parentheses, there are NO ABBIENTS. You must call the function if you have a list of arguments in parentheses.

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 a function name as a function pointer equivalent to applying an operator address to a function name?

+5
source share

All Articles