[SOLVED] I am not getting how the structure is being passed to a function in following code using call by reference?

Issue

Like in this code, what I don’t understand is how ‘n1’ [ increment(n1) ] is being passed to ‘number& n2’[void increment(number& n2)].
how can we pass n1 into &n2?
Please let me know if I am getting the basics wrong, because its only recently that i have started to learn C and C++.

// C++ program to pass structure as an argument
// to the functions using Call By Reference Method

#include <bits/stdc++.h>
using namespace std;

struct number {
    int n;
};

// Accepts structure as an argument
// using call by reference method
void increment(number& n2)
{
    n2.n++;
}

void initializeFunction()
{
    number n1;

    // assigning value to n
    n1.n = 10;

    cout << " number before calling "
        << "increment function:"
        << n1.n << endl;

    // calling increment function
    increment(n1);

    cout << "number after calling"
        << " increment function:" << n1.n;
}

// Driver code
int main()
{
    // Calling function to do required task
    initializeFunction();

    return 0;

Solution

Since you are taking the parameter to increment function as a refrence so when you pass n1 to it as follows:

increment(n1);

It is passed as a reference to the increment function which basically means that alias of n1 is created with the name n2
void increment(number& n2)
This means whenever there is a change in n2, It is also reflected in n1(Because they are refering to the same location)

Also, passing a variable as Reference means allowing a function to modify a variable without creating a copy of it by declaring reference variables. The memory location of the passed variable and parameter is the same and therefore, any change to the parameter reflects in the variable itself.

So, after the function call:
n1.n is incremented

Answered By – Khushi Bhambri

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.