BobAlmond
BobAlmond

Reputation: 903

C++ pointer to functions, Beginner Question

I want to ask about pointer in C++

I have some simple code:

int add(int a, int b){
 return a+b;
}

int runner(int x,int y, int (*functocall)(int, int)){
 return (*functocall)(x,y);
}

now, suppose I call those functions using this way :

cout<<runner(2,5,&add);

or maybe

cout<<runner(2,5,add);

is there any difference? because when I tried, the result is the same and with no error.

Thanks a lot

Upvotes: 19

Views: 399

Answers (6)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506897

Notice that you can have references to functions

int runner(int x,int y, int (&functocall)(int, int)){
 return functocall(x,y);
}

Now calling it with &add won't work anymore because you try to bind a function reference to a pointer instead of to a function. Sometimes this shines through when using templates

template<typename T>
int runner(int x,int y, T &functocall, T otherfunc){
 return functocall(x,y) + otherfunc(y, x);
}

Now calling it with runner(10, 20, add, add) will fail because T is tried to be deduced to both a function pointer and a function type (no decay to a pointer is done when passing to a reference parameter!).

Upvotes: 1

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99565

Function will be implicitly casted to a pointer according to C++ Standard (4.3/1). There is no difference. However this conversion never applies to nonstatic member functions. For them you should explicitly write &.

Upvotes: 10

Jerry Coffin
Jerry Coffin

Reputation: 490098

No, in this particular case there is no difference. Either one gives you the address of the function.

Note, however, that in C++, getting a pointer to a member function requires that you use the '&' operator.

Upvotes: 3

Andrey
Andrey

Reputation: 60065

it is because there is no such object (in terms of expressions) as function, there are only pointers to functions. When you want to pass function to your function the only thing you can actually pass is pointer, so compiler does this cast for you

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

There is no difference. For consistency with other ways of getting a pointer you can use &, but the name by itself would have no other meaning so it is assumed to mean "get the address".

It's very similar to array variable names acting as the address of the first element of the array.

Upvotes: 3

John Weldon
John Weldon

Reputation: 40739

I believe the second call automatically resolves to the first call in the compiler...

Upvotes: 0

Related Questions