Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When doing Function Pointers what is the purpose of using the address-of operator vs not using it?

Tags:

c++

c

For the following code snippets why would I use one assignment vs another? thx

void  addOne(int &x)
{
    x +=1;
}

void (*inc)(int &x) = addOne;   // what is the purpose of doing "addOne" 
void (*inc)(int &x) = &addOne;  //  vs &addOne ??  

int a = 10;
inc(a);
like image 534
jdl Avatar asked Mar 31 '12 16:03

jdl


2 Answers

The purpose of one over the other is C compatibility. C said that functions will decay to pointers-to-functions automatically. To be compatible, C++ had to do the same.

Note that when C++ introduced a new function pointer type (member function pointers), they do not decay automatically. So if the C++ committee had their way, odds are good you'd need that & there.

like image 106
Nicol Bolas Avatar answered Oct 24 '22 11:10

Nicol Bolas


Brevity, style. It's the same with using * when calling them.

Also note array vs &array[0].

like image 29
aib Avatar answered Oct 24 '22 11:10

aib