In C , passing arguments to functions by reference or pointer is a common practice for modifying the actual values outside the function scope. However, understanding when to use which can be confusing.
Passing by Reference
Passing by reference allows direct access and modification of the original variable. It is useful for:
Passing by Pointer
Passing by pointer provides indirect access to the variable through a pointer. It is necessary when:
Good Practices
As a general guideline, it is recommended to use references when:
Use pointers when:
Example
The following snippet demonstrates a common scenario where a reference is used to pass a large object:
void foo(std::string& s) { s += "suffix"; }
Passing by pointer would be suitable in this case if the function needed to create a new string object:
void foo(std::string* s) { *s = "new string"; // Deallocates the old string }
In rare cases, passing by value may also be appropriate, such as when copying a small immutable object (e.g., a primitive type) is not an issue.
The above is the detailed content of When Should You Use References vs. Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!