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;
A function is already a pointer; therefore, you do not need the address operator.
Brevity, style. It's the same with using *
when calling them.
Also note array
vs &array[0]
.
From the book C++ Programming Languauge, it is cleary indicated that &
and *
operators are optional for pointers to functions:
There are only two things one can do to a function: call it and take its address. The pointer obtained by taking the address of a function can then be used to call the function. For example:
void error (string s) { /* ... */ } void (*efct )(string ); // pointer to function void f () { efct = &error ; // efct points to error efct ("error "); // call error through efct }
The compiler will discover that efct is a pointer and call the function pointed to. That is, dereferencing of a pointer to function using * is optional. Similarly, using & to get the address of a function is optional:
void (*f1 )(string ) = &error ; // ok void (*f2 )(string ) = error ; // also ok; same meaning as &error void g () { f1 ("Vasa"); // ok (*f1 )("Mary Rose"); // also ok }
As others pointed out, pointer to member function is new/different in C++. The &
is not optional to point a member and it is explained as (in C++ Programming Languauge Book):
A pointer to member can be obtained by applying the address-of operator & to a fully qualified class member name, for example, &Std_interface::suspend.
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.