Search code examples
c++parameter-passingfunction-pointersimplicit-conversionfunction-declaration

Passing a function to another function via "pass by value"


Code

void printA()
{
   cout << "A\n";
}

void print1( void (*func_ptr)(void) )
{
   func_ptr();
}

void print2( void func(void))
{
   func();
}

int main()
{
  //Method 1a (passing function pointer)
  print1(&printA);
  //Method 1b (why does it work even though I didn't pass a reference or a pointer?)
  print1(printA);

  //Method 2 (passing the whole function ?)
  print2(printA);

  return 0;
}

Method 1a makes sense: print1 was expecting a reference or pointer.
Question 1:
Method 1b does not make sense: Why doesn't the compiler throw an error. Why does it work, even though I didn't pass the reference or the pointer of printA() to print1()?
Question 2:
Method 2a implies a new copy of the function printA() is made and passed to function print2(). In other words, is the function printA() is passed to function print2() by value?
Question 3:
Are identifiers of functions references? (this might help)
Much appreciated thanks.


Solution

  • The parameter of this function declaration

    void print2( void func(void));
    

    is adjusted by the compiler to pointer to the function type that is to

    void print2( void ( *func )(void));
    

    The both above declarations declare the same one function and may be both present in the same compilation unit though the compiler can issue a message that there are redundant function declarations.

    On the other hand, a function designator used as an argument for such a function shown above is implicitly converted to a pointer to the function.

    You may even write for example

    print2(**********printA);
    

    Thus as for this your question

    Method 2a implies a new copy of the function printA() is made and passed to function print2(). In other words, is the function printA() is passed to function print2() by value?

    then neither copy of the function is passed. It is a pointer to the function that is passed.