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?
* can be either the dereference operator or part of the pointer declaration syntax. & can be either the address-of operator or (in C++) part of the reference declaration syntax.
The ampersand is the address of operator. It returns the memory location of a variable and that's the only way it's used, prefixed to a variable like the engine on a train. The variable doesn't even have to be initialized, just declared.
In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199).
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.
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.
Both do the same, but one uses references and one uses pointers.
See my answer here for a comprehensive list of all the differences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With