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

When Should I Use References vs. Pointers in C ?

Linda Hamilton
Release: 2024-11-13 12:26:02
Original
252 people have browsed it

When Should I Use References vs. Pointers in C  ?

Passing by Reference vs. Pointer in C

In C , understanding when to use references and pointers can be a confusing topic. This article explores the nuances of passing by reference and by pointer, providing practical guidelines.

Pass by Reference:

Passing by reference is recommended when you need to:

  • Modify the actual value of the passed variable.
  • Pass complex objects (e.g., strings, vectors) efficiently, avoiding the overhead of copying.

Pass by Pointer:

Passing by pointer is necessary when:

  • You cannot pass a temporary object by reference (since a reference must bind to an existing object).
  • You need to pass a null pointer.
  • You need to change the pointer itself, not its target (e.g., assign a new value to the pointer).

Best Practices:

As a general rule, prefer passing by reference whenever possible. However, when dealing with literals, null pointers, or situations where you need to modify the pointer itself, pass by pointer.

Example:

The code snippet provided passes a pointer to a dynamically allocated vector to a map. This is a valid approach because we need to both create a new vector and pass it by reference to the map. By using pointers, we avoid the need to copy the entire vector.

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <tr1/memory>
#include <algorithm>
using namespace std;
using namespace std::tr1;

int main(){
        map<string, shared_ptr<vector<string>>> adjacencyMap;
        vector<string>* myFriends = new vector<string>();
        myFriends->push_back(string("a"));
        myFriends->push_back(string("v"));
        myFriends->push_back(string("g"));
        adjacencyMap["s"] = shared_ptr<vector<string>>(myFriends);
        return 0;
}
Copy after login

The above is the detailed content of When Should I 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