Passing Arguments by Value vs Reference in C++
What is the difference between passing function arguments by value and by reference?
When you pass an argument by value, a copy of the argument is made and used within the function. Changes to this copy do not affect the original argument.
When you pass an argument by reference, the function gets a reference to the original argument. Changes made to the reference will affect the original argument.
Here's an example:
#include <iostream>
void PassByValue(int x) { x = 10; }
void PassByReference(int& x) { x = 10; }
int main() {
int value = 5;
PassByValue(value);
std::cout << value << std::endl; // Outputs 5
PassByReference(value);
std::cout << value << std::endl; // Outputs 10
}
5
10
Passing by reference is useful when you want the function to modify the original argument, or when you want to avoid the overhead of copying large objects.
Introduction to Functions
Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.