HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Should I use a pointer or a reference to remotely assign a variable?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
pointerremotelyshouldusevariableassignreference

Problem

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.

Context

Stack Overflow Q#114180, score: 307

Revisions (0)

No revisions yet.