Passing data to a function is very important and is often used at times in writing the code.
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.
Now, If You Know the Prerequisites, you can move forward.
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;
}
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.
The time complexity of programs using pass-by-value or pass-by-reference is almost similar.
Thank you so much for reading this!
The featured image is taken from here.