Difference Between Call by Value and Call by Reference in C++

Difference between Call by value and Call by Reference in C++: As we have already regarding the call by value, reference, and address. Now let us learn the differences between them.

Difference between Call by value and Call by Reference in C++

 

Call By Value Call By Reference
While calling functions, we pass the values of variables to it. These functions are known as “Call By Values”. While calling a function, instead of passing the values of variables, we are passing the address of variables to the function known as “Call By References.
The value of each variable in the calling function is copied into corresponding duplicate variables of the called function. The address of actual variables in the calling function is copied into the dummy variables of the called function
Changes made to the duplicate variables in the called function have no effect on the values of actual variables in the calling function Using addresses we would have access to the actual variables and hence we would be able to manipulate
In call by values, we cannot alter the values of actual variables through function calls In call by reference, we can alter the values of variables through function calls
Values of variables are passed by Simple technique Pointer variables are necessary to define to store the address values of variables

Example: for Call By Value

#include <stdio.h>   
// Function Prototype 
void swapx(int x, int y);   
// Main function 
int main() 
{ 
    int a = 10, b = 20;  
//Pass by Values 
swapx(a, b);   
printf("a=%d b=%d\n", a, b); 
  return 0; 
} 
//Swap functions that swaps 
//two values 
void swapx(int x, int y) 
{ 
    int t;   
    t = x; 
    x = y; 
    y = t;   
    printf("x=%d y=%d\n", x, y); 
}

Output:

x=20 y = 10
a=10 b = 20

Example: Call By Reference

#include <stdio.h>   
//Function Prototype 
void swapx(int*, int*); 
// Main function 
int main() 
{ 
    int a = 10, b = 20; 
//Pass reference 
   swapx(&a, &b); 
   printf("a=%d b=%d\n", a, b); 
   return 0; 
 } 
//Function to swap two variables by references 
void swapx(int* x, int* y) 
{ 
    int t; 
    t = *x; 
    *x = *y; 
    *y = t; 
    printf("x=%d y=%d\n", *x, *y); 
}

Output:

x=20 y =10
a=20 b =10