Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
} 
like image 670
Handsomeguy123 Avatar asked Nov 12 '15 16:11

Handsomeguy123


1 Answers

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?

like image 55
Toby Liu Avatar answered Sep 22 '22 18:09

Toby Liu