c-plus-plus
  1. c-plus-plus-call-by-value-reference

C++ Functions Call by Value & Reference

Syntax

return_type function_name(parameter_type parameter_name);

Call by Value

void function_name(int x) {
    statement(s);
}

Call by Reference

void function_name(int& x) {
    statement(s);
}

Example

Call by Value

#include<iostream>
using namespace std;
void swap(int a,int b)
{
    int temp=a;
    a=b;
    b=temp;
    cout<<"a: "<<a<<" b: "<<b<<endl;
}

int main()
{
    int x=10,y=20;
    swap(x,y);
    cout<<"x: "<<x<<" y: "<<y<<endl;
    return 0;
}

Output

a: 20 b: 10
x: 10 y: 20

Explanation

In this example, we are trying to swap two integers using call by value function. But since the values of a and b in the function swap() are passed by value, the changes are not reflected outside the function and therefore the values of x and y remain unchanged.

Call by Reference

#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
    int temp=a;
    a=b;
    b=temp;
    cout<<"a: "<<a<<" b: "<<b<<endl;
}

int main()
{
    int x=10,y=20;
    swap(x,y);
    cout<<"x: "<<x<<" y: "<<y<<endl;
    return 0;
}

Output

a: 20 b: 10
x: 20 y: 10

Explanation

In this example, we are trying to swap two integers using call by reference function. The values of a and b in the function swap() are passed by reference, so any changes made to them within the function are reflected outside the function. Therefore, the values of x and y are swapped.

Use

  • Call by value is used when you want to copy the value of the parameter into a function.
  • Call by reference is used when you want to pass the reference of the parameter into a function.

Important Points

  • In call by value, the values of the parameters are copied into the function.
  • In call by reference, the reference of the parameters is passed into the function.
  • Call by value does not reflect changes made to the parameter outside the function.
  • Call by reference reflects changes made to the parameter outside the function.

Summary

In C++ Functions, we can either pass the parameters by value or by reference. In call by value, the values of the parameters are copied into a function. Whereas in call by reference, the reference of the parameters is passed into a function. In call by value function, changes made to the parameters are not reflected outside the function and in call by reference function, changes made to the parameters are reflected outside the function.

Published on: