Handsomeguy123
Handsomeguy123

Reputation: 147

Function Pointer - 2 options

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);
} 

Upvotes: 8

Views: 142

Answers (1)

Toby Liu
Toby Liu

Reputation: 1267

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?

Upvotes: 5

Related Questions