Pass-by-Value vs Pass-by-Reference
Compare semantic and performance differences between passing by value and by reference.
Pass-by-Value Recap
When you pass an argument by value, the function gets a copy. Changes inside the function do not affect the caller.
void increment(int x) {
x++; // modifies the copy
}
int n = 5;
increment(n);
std::cout << n; // still 5Pass-by-Reference
Pass by reference using & in the parameter list. The function works directly on the caller s variable.
void increment(int& x) {
x++;
}
int n = 5;
increment(n);
std::cout << n; // now 6All lessons in this course
- Why References Aliases for Variables
- Pass-by-Value vs Pass-by-Reference
- const References and When to Use Them
- Reference Lifetime and Dangling References