c++ pass by reference vs pass by value code example
Example 1: pass by value and pass by reference c++
#include <iostream>
using namespace std;
void by_value(int x) {
x *= 2;
}
void by_reference(int &x) {
x *= 2;
}
int main() {
int a1 = 5, a2 = 5;
cout << "Before: a1 = " << a1 << ", a2 = " << a2 << "\n";
by_value(a1);
by_reference(a2);
cout << "After: a1 = " << a1 << ", a2 = " << a2 << "\n";
return 0;
}
Example 2: copy by reference copy by value
main() {
int i = 10, j = 20;
swapThemByVal(i, j);
cout << i << " " << j << endl; // displays 10 20
swapThemByRef(i, j);
cout << i << " " << j << endl; // displays 20 10
...
}
void swapThemByVal(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
void swapThemByRef(int& num1, int& num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}