Pointer vs. Reference

Jack Reza picture Jack Reza · Sep 22, 2008 · Viewed 112.2k times · Source

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?

Answer

Nils Pipenbrinck picture Nils Pipenbrinck · Sep 22, 2008

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.