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


Question

Is there some kind of subtle difference between those:

void a1(float &b) {
    b=1;
};
a1(b);

and

void a1(float *b) {
    (*b)=1;
};
a1(&b);

?

They both do the same (or so it seems from main() ), but the first one is obviously shorter, however most of the code I see uses second notation. Is there a difference? Maybe in case it's some object instead of float?

1
65
2/27/2009 9:01:18 PM

Accepted Answer

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

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

52
5/23/2017 11:54:53 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon