When using function pointers, what is the purpose of using the operator address, not its use?

For the following code snippets, why should I use one assignment instead of another? thanks

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); 
+8
c ++ c
source share
4 answers

The goal of one over the other is C compatibility. C said that functions automatically break up into function pointers. To be compatible, C ++ had to do the same.

Note that when C ++ introduces a new type of function pointer (member function pointers), they do not break up automatically. So, if the C ++ committee had its own way, the chances are good, you'll need & .

+9
source share

Brevity, style. The same with * when calling them.

Also pay attention to array vs &array[0] .

+3
source share

From the C ++ book Programming Languauge , this suggests that the & and * operators are optional for function pointers:

There are only two things you can do with a function: name it and take its address. The pointer obtained by determining the address of the 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 detect that efct is a pointer and call the function it points to. That is, dereferencing a function pointer using * is optional. Similarly, using and 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 noted, a pointer to a member function is new / different in C ++. & is not optional for specifying an element and is explained as (in a C ++ Programmer):

A pointer to a member can be obtained by applying the address of the operator to the fully qualified name of the class member, for example, & amp ;. Std_interface :: pause

0
source share

The function is already a pointer; therefore you do not need an address operator.

-one
source share

All Articles