C++ | Call By Value and Call By Reference

Updated: Jun 11

We can pass the information to the called function in two ways-

  1. Call By Value

  2. Call By Reference

Call By Value-: When formal arguments are ordinary variables,it is function call by value.In call-by-value,the called function does not have access to the actual variables in the calling program and only works on the copies of the values.This mechanism is fine if the function does not need to alter the values of the original variables in the calling function.Thus,original value is not modified.

The following program demonstrates how the information is passed to the called function by passing the value of parameters.

#include <iostream>
using namespace std;
int sum (int,int);
int main()
{
    int a=10,b=20;
    int s=sum(a,b);
    cout<<"sum is "<<s;
}
int sum(int x,int y)
{
    return(x+y);
}
Output:
sum is 30

Call By Reference: When formal arguments are reference variables ,it is call by reference.If we would like to vary the value of variables within the calling program,we pass the parameters to the function by reference .In call by reference ,original value is modified because we pass reference(address).Here, address of the value is passed within the function, so actual and formal arguments share an equivalent address space. Hence, value changed inside the function, is reflected inside also as outside the function.

Let's attempt to understand the concept of call by reference in C++ language by the instance given below:

#include<iostream>
using namespace std;
int sum (int &,int &);
int main()
    {
    int a=50,b=60;
    int s=sum(a,b);
    cout<<"sum is "<<s;
}    
    int sum(int &x,int &y)
    {
    return(x+y);
}
Output:
sum is 110

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science

20 views

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door