C++ – Reference vs. Pointer Explained

c++pointersreference

What is the difference? Because this:

int Value = 50;
int *pValue = &Value;

*pValue = 88;

and ref version do the same:

int Value = 50;
int &rValue = Value;

rValue = 88;

Which one is better to use? Thanks.

Best Answer

In this case, they are equivalent.

It does not matter which you use, and neither is "best".

If you really want to choose between them then the reference is probably more idiomatic. I generally stick to references wherever I can because my OCD likes it: they feel "tighter", cannot be re-bound (with or without you noticing) and don't require a dereference to get to the value.

But I'm not aware of any general consensus on the issue for cases such as this.

Also note that the two may not compile to the same code if your implementation does not implement references with pointers, though I know of no implementation like that, and you wouldn't notice the difference anyway.