Home > Backend Development > C++ > When Should You Use References vs. Pointers in C ?

When Should You Use References vs. Pointers in C ?

Barbara Streisand
Release: 2024-11-20 14:45:17
Original
522 people have browsed it

When Should You Use References vs. Pointers in C  ?

Understanding Passing by Reference and Pointer in C

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:

  • Mutating large objects (e.g., strings, vectors) to avoid unnecessary copying.
  • Passing in-out arguments where both functions use the same variable.

Passing by Pointer

Passing by pointer provides indirect access to the variable through a pointer. It is necessary when:

  • The pointer needs to be manipulated (e.g., reassigning to a new object).
  • Passing a null value, which is not allowed for references.
  • Preventing modifications of the original variable (pass a const pointer).

Good Practices

As a general guideline, it is recommended to use references when:

  • You want to mutate the original variable.
  • You have a non-null value to pass.
  • The original variable is not excessively large.

Use pointers when:

  • You need to manipulate the address of the variable.
  • You have nullable values.
  • You want to prevent modifications of the original variable.

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";
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template