Pass by value and reference
There are two ways for passing a value to a function : pass by value and pass by reference.The original value is not modified in pass by value but is modified in pass by reference.
Pass by reference Pass by reference is also known as pass by address or call by reference. While calling a function, instead of passing the values of variables, we pass a reference to values.
Let’s understand the flow:
•We pass in the actual parameters.
•A reference variable is created and passed to the function.
•A reference variable is a nickname for any variable.
#include <iostream>
// function to swap values
void swap(int* a, int* b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
// main function
int main() {
int x = 5, y = 15;
//pass by reference
swap(&x, &y);
std::cout << "x:" << x << ", y:" << y;
return 0;
}
Output:
x: 15, y: 5
Pass by Value in C++Pass by value is also known as pass by copy or call by value. By definition, pass by value means to pass in the actual parameter’s copy in memory as the formal parameters.
To say it in simpler terms, let’s understand what happens when we pass a value to a function via pass by value:
We pass in the actual parameters.
A copy of the same is created in the memory.
This copy is passed as the formal parameters.
#include <iostream>
// function to swap two values
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
}
// main function
int main() {
int x = 5, y = 15;
// pass by values
swap(x, y);
std::cout << "x:" << x << ", y:" << y;
return 0;
}
Output
x: 5, y: 15