Call by reference in cpp

Call by reference in cpp is one approach to implement function ( to call function)

In this tutorial we will see what is function, call by reference and program  for call by reference.

What is function :  function is block of code.

Call by reference: When function are called by passing the address they are called as call  by reference. its alse called as call by address in c++.

What is reference variable : It is one of the analysis all the other names given to the memory location. In short reference are the multiple names given to the same memory locations.

Call by reference example 

C++ function call by reference

C++ function call by reference

Call by reference program in c++

12345678910111213141516171819202122232425262728#include <iostream>using namespace std;void swap(int *x ,int *y );//Call By refernceint main(){    int a,b;    cout<<“\nEnter Two Number To Swap :\n”;    cin>>a>>b;cout<<“\n Before Numbers :\n\n”; cout<<“x= “<<a<<”   “<<“y= “<<b<<” \n”;    cout<<“\nAfter Swapping Numbers :\n\n”;    swap(&a,&b);     cout<<“x= “<<a<<”   “<<“y= “<<b<<” \n”;    return 0;}void swap(int *x,int *y){ int z; z=*x; *x=*y; *y=z; }

Output :

C++ Program To Swap Two Numbers Using Functions
C++ Program To Swap Two Numbers Using Functions

Explanation :

1. First we declare the function which is swap function

=> void swap(int *x ,int *y);

2. Execution starts with the main method.

3. Declare the variables

a, b => to store two numbers

4. Take a input from user two numbers

=>  cin>>a>>b;   a = 10, b= 20

5. We print numbers before swapping.

6. Next we call function by passing address of a and b

swap(&a,&b);  => function get executed

swap(int *x,int  *y) {   => x= 10 y = 20

*z=*x;   => *z=10

*x=*y;  => *x=20

*y=*z;  =>*y = 10

} => Returns to main function

7. Now we print numbers after swapping

cout<<“x= “<<x<<” “<<“y= “<<y<<” \n”;

8. End with the program.