Reference Parameters in C++ Tutorial

With Reference parameters you are actually creating an alias(another name) to the existing variable.

Use case where Reference Parameters are required:

1. Return More than one Value: A function can return only one value, what if you are having a situation where you function has to modify more than one value and return it to the caller. By using reference parameters you can modify more than one value in the function.

What happens when a reference parameter is declared?

When you pass a reference parameters , instead of copying the actual value, the memory address is copied into the formal parameter.

How to differentiate between a simple parameter and a reference parameter?

We use an ampersand(&) operator to indicate the parameter is a reference parameter. 
Eg: int &a; //Reference parameter
      int a; // Not a reference parameter

Swap Example Using Reference Parameters:

#include <iostream>

using namespace std;

void swap(int &num1, int &num2)
{
     num1 = num1 + num2;
     num2 = num1 - num2;
     num1 = num1 - num2;
}


int main()
{
    int number1 = 5;
    int number2 = 10;
    cout << "Values Before Swapping" <<endl;
    cout << "Number 1:" << number1 << endl;
    cout << "Number 2:" << number2 << endl;
    swap(number1, number2);
    cout << "Values After Swapping" <<endl;
    cout << "Number 1:" << number1 << endl;
    cout << "Number 2:" << number2 << endl;

    return 0;
}

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig