×

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++

Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have the same result. So the remaining statements are inevitable; when one is over the other significant? What are the causes we’re using one over another?

Passing by Pointer:

// C++ program for swaping two numbers with pass-by-pointer.
#include <iostream>
using namespace std;
void swap(int* t, int* p)
{
    int k = *t;
    *t = *p;
    *p = k;
}
int main()
{
    int s = 78, c = 55;
    cout << "Before Swap\n";
    cout << "s = " << s << " c = " << c << "\n";
    swap(&s, &c);
    cout << "After Swap with pass by pointer\n";
    cout << "s = " << s << " c = " << c << "\n";
}

Output:

Passing by Reference vs Pointer in C++

Passing by Reference:

// C++ program to swap two numbers using
// pass by reference.
#include <iostream>
using namespace std;
void swap(int& w, int& q)
{
    int l = w;
    w = q;
    q = l;
}
int main()
{
    int n = 122, m = 210;
    cout << "Before Swap\n";
    cout << "n = " << n << " m = " << m << "\n";
    swap(n, m);
    cout << "After Swap with pass by reference\n";
    cout << "n = " << n << " m = " << m << "\n";
}

Output:

Passing by Reference vs Pointer in C++

The difference in between Reference variable and pointer variable

  • Generally, references are applied with pointers. A reference is the same object; it only has to refer to an entity with a different name and context. They are safer to use as references cannot be NULL.
  • A pointer may be reassigned while the relation cannot be assigned and must only be allocated at initialization.
  • The pointer is explicitly assignable to NULL, while reference cannot.
  • Pointers may append over an array, and we can use + + to move towards the next object a pointer points toward.
  • The variable is a way that has an address to the memory. A reference has the same address as the object it is referring to.
  • A class or struct pointer requires' ->'(arrow operator) to reach its members while a reference uses a. '(dot operator)
  • To access the memory location it refers to, a pointer must be dereferenced with *, while a pointer can be substituted directly.
// C++ program to display variations between reference and pointer.
#include <iostream>
using namespace std;
struct demo
{
    int s;
};
int main()
{
    int m = 3;
    int n = 8;
    demo d;
    int *k;
    k =  &m;
    k = &n;                     // 1. Pointer reintialization allowed
    int &t = m;
    // &r = y;                  // 1. Compile Error
    t = n;                      // 1. m value becomes 3
    k = NULL;           
    // &r = NULL;               // 2. Compile Error
    k++;                        // 3. Points to next memory location
    t++;                        // 3. m values becomes 8
    cout << &k << " " << &m << endl;    // 4. Different address
    cout << &t << " " << &m << endl;    // 4. Same address
    demo *q = &d;
    demo &qq = d;
    q->s = 9;
    // q.s = 9;                 // 5. Compile Error 
    qq.s = 9;
    // qq->s = 9;               // 5. Compile Error
    cout << k << endl;       
    cout << t << endl;            
    return 0;
}

Output:

Passing by Reference vs Pointer in C++

Related Topics

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.