8

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);
} 
  • 1
    Function parameter declarations are adjusted to pointer-to-function type. They are both equivalent. – David G Nov 12 '15 at 16:21

1 Answers1

5

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?

Community
  • 1
  • 1
Toby Liu
  • 1,267
  • 9
  • 14