C++: difference between ampersand "&" and asterisk "*" in function/method declaration?

Both do the same, but one uses references and one uses pointers.

See my answer here for a comprehensive list of all the differences.


Yes. The * notation says that what's being pass on the stack is a pointer, ie, address of something. The & says it's a reference. The effect is similar but not identical:

Let's take two cases:

   void examP(int* ip);
   void examR(int& i);

   int i;

If I call examP, I write

   examP(&i);

which takes the address of the item and passes it on the stack. If I call examR,

   examR(i);

I don't need it; now the compiler "somehow" passes a reference -- which practically means it gets and passes the address of i. On the code side, then

   void examP(int* ip){
        *ip += 1;
   }

I have to make sure to dereference the pointer. ip += 1 does something very different.

   void examR(int& i){
        i += 1;
   }

always updates the value of i.

For more to think about, read up on "call by reference" versus "call by value". The & notion gives C++ call by reference.


In the first example with references, you know that b can't be NULL. With the pointer example, b might be the NULL pointer.

However, note that it is possible to pass a NULL object through a reference, but it's awkward and the called procedure can assume it's an error to have done so:

a1(*(float *)NULL);

In the second example the caller has to prefix the variable name with '&' to pass the address of the variable.

This may be an advantage - the caller cannot inadvertently modify a variable by passing it as a reference when they thought they were passing by value.


Aside from syntactic sugar, the only real difference is the ability for a function parameter that is a pointer to be null. So the pointer version can be more expressive if it handles the null case properly. The null case can also have some special meaning attached to it. The reference version can only operate on values of the type specified without a null capability.