3
#include <iostream>
#include <algorithm>
using namespace std;

bool myfn(int i, int j) { return i<j; }



int main () {
int myints[] = {3,7,2,5,6,4,9};

 // using function myfn as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;

return 0;
}

considering the above code , is there any difference if we passmyfn or &myfn to min_element? when we tried to pass a functor which one would be a more standard way?

SJinxin
  • 75
  • 7
  • See http://stackoverflow.com/questions/6893285/why-do-all-these-crazy-function-pointer-definitions-all-work-what-is-really-goi – Mankarse Aug 28 '12 at 16:48

2 Answers2

10

Typically, pass-by-reference and pass-by-value only refer to passing variables, not functions. (Template functions introduce some complications, but that is for another discussion.) Here you are passing myfn as a pointer to a function. There is no difference if you use &myfn instead. The compiler will implicitly convert myfn to a pointer to the function with that name.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 1
    That's not entirely true. You can have a function template deduce a function *reference* type as well as a pointer type... – Kerrek SB Aug 28 '12 at 16:52
  • @KerrekSB I'm not all that familiar with that part of template programming. I have updated my answer to take that into account. Thanks for pointing it out! – Code-Apprentice Aug 28 '12 at 16:58
  • OK, if you have `void f();` and `template bar(R(&func)(Args...));`, then when you call `bar(f)`, `func` will be deduced as a function *reference*. However, *saying* a function reference immediately makes it decay to a function pointer... – Kerrek SB Aug 28 '12 at 17:01
  • @KerrekSB As I stated in my edit, the complications from templates aren't germane to this particular question and should be post-poned for another discussion if they become an issue. – Code-Apprentice Aug 28 '12 at 17:33
6

is there any difference if we pass myfn or &myfn to min_element?

No. myfn gets implicitly converted into pointer-to-function, anyway. So there is no difference at all.

Nawaz
  • 353,942
  • 115
  • 666
  • 851