Abstract

Passing data to a function is very important and is often used at times in writing the code.

Scope of the Article

Note
For the scope of this article, we will use Call-By-Value and Pass-By-Value interchangeably similar is the case for Call-By-Reference and Pass-By-Reference. You can learn more about the differences here.

Prerequisites

Now, If You Know the Prerequisites, you can move forward.

Pass-By-Value

Example Code 1
#include<bits/stdc++.h>
void add(int x,int y)
{
      x=x+y;
      return;
}
int main()
{
       
int x=5;
int y=6;
 
add(x,y); // passing by value the parameters (x,y). 
 
cout<<x<<"\n";
return 0;
What do you think the value of x will be?
A.)  5
B.) 11
Notice one thing carefully: we have passed the parameters x and y with value. Meaning the add function only has a copy of their value, not the memory address.
So the update of (x=x+y) has a local scope inside the add function only. After the function call ends, the value of variable x will be the same as the previous, i.e., 5.
Example Code 2
#include<bits/stdc++.h>
using namespace std;
 
void swapValues(int x,int y)
{
    swap(x,y);
      return;
}
int main()
{
       
int x=5;
int y=6;
 
swapValues(x,y); // passing by value the parameters (x,y). 
 
cout<<x<<"\n";
return 0;
}

When to use Pass-By-Value

Pass-By-Reference

Example Code
#include<bits/stdc++.h>
using namespace std;
 
// Taking the values of x and y with reference.
void swapValues(int &x,int &y)
{
    swap(x,y);
      return;
}
int main()
{
       
int x=5;
int y=6;
 
swapValues(x,y); // passing by reference the parameters (x,y). 
 
cout<<x<<"\n";
return 0;
}

Here notice one thing carefully: we have taken the values of x and y using the ampersand operator (&), meaning we are taking values by reference using the actual memory address of the variables.
So after the function calls end. The value of x will be swapped with the value of y.

When to use Pass-By-Reference

Time Complexity

The time complexity of programs using pass-by-value or pass-by-reference is almost similar.

Key Points and Conclusion

  1. Both are equally important features of C/C++ pass-by-value and are mostly used over pass-by-reference.
  2. A copy of the same variable is stored in the call stack during the function call.
  3. As per the needs of the program, the choice between pass-by-value and pass-by-reference has to be made.
Thank you so much for reading this!
The featured image is taken from here.