Best Practice for Remotely Assigning Variables: Pointers vs. References
When passing variables to functions for remote assignment, there are two options: pointers and references. Both serve different purposes, but which is the better choice?
Pointers vs. References: A Closer Look
Pointers:
References:
When to Use Pointers:
Use pointers if your function requires:
When to Use References:
Use references in most other cases:
In the example provided:
unsigned long x = 4; void func1(unsigned long& val) { val = 5; } func1(x);
Using a reference here is better practice because it provides a direct reference to the original variable x, modifying it directly.
void func2(unsigned long* val) { *val = 5; } func2(&x);
While a pointer could also achieve this, it is more verbose and prone to errors. The rule of thumb is to use pointers for pointer arithmetic or passing NULL-pointers; otherwise, references are the preferred choice.
The above is the detailed content of Pointers or References: Which is Best for Remote Variable Assignment?. For more information, please follow other related articles on the PHP Chinese website!