Programming
c++ variables pointers reference
Updated Fri, 22 Jul 2022 03:58:52 GMT

Pointer vs. Reference


What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;
void func1(unsigned long& val) {
     val = 5;            
}
func1(x);

or:

void func2(unsigned long* val) {
     *val = 5;
}
func2(&x);

IOW: Is there any reason to pick one over another?




Solution

My rule of thumb is:

Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.

Use references otherwise.





Comments (5)

  • +0 – Excelent point regarding a pointer being NULL. If you have a pointer parameter then you must either check explicitly that it is not NULL, or search all usages of the function to be sure that it is never NULL. This effort is not required for references. — Sep 22, 2008 at 11:10  
  • +0 – Explain what you mean by arithmetic. A new user may not understand that you want to adjust what the pointer is pointing at. — Sep 22, 2008 at 16:30  
  • +8 – Martin, By arithmetic I mean that you pass a pointer to a structure but know that it's not a simple structure but an array of it. In this case you could either index it using [] or do arithmetic by using ++/-- on the pointer. That's the difference in a nutshell. — Nov 25, 2008 at 20:35  
  • +2 – Martin, You can only do this with pointers directly. Not with references. Sure you can take a pointer to a reference and do the same thing in practice, but if you do so you end with very dirty code.. — Nov 25, 2008 at 20:38  
  • +1 – What about polymorphism (e.g. Base* b = new Derived())? This seems like a case that can't be handled without pointers. — Mar 07, 2013 at 19:25