Pass by Value vs Pass by Reference in C++
Definition in C++:
1. Pass by Value:
- In pass by value, the function gets a COPY of the original variable.
- Changes made to the parameter inside the function do NOT affect the original variable.
Example:
#include <iostream>
using namespace std;
void change(int num) {
num = 10;
cout << "Inside function: " << num << endl;
int main() {
int x = 5;
change(x);
cout << "Outside function: " << x << endl; // x is still 5
return 0;
2. Pass by Reference:
- In pass by reference, the function gets DIRECT access to the original variable using &.
- Changes made to the parameter inside the function DO affect the original variable.
Example:
#include <iostream>
using namespace std;
void change(int &num) {
num = 10;
cout << "Inside function: " << num << endl;
int main() {
int x = 5;
change(x);
cout << "Outside function: " << x << endl; // x becomes 10
return 0;
Why use Pass by Reference?
- When you want the function to modify the original variable.
- When passing large data like arrays or objects to save memory.
Why use Pass by Value?
- When you only want to read the data.
- When you want to keep the original data safe from being changed.