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.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Default Arguments in C++ Functions
In what situations is it beneficial to use default arguments for function parameters?
Best Practices for Function Overloading in C++
What are some best practices to follow when overloading functions in C++?
When to Use Forward Declarations in C++
In what situations should I use forward declarations in my C++ code?
Pros and Cons of Global Variables in C++
What are the advantages and disadvantages of using global variables in C++?
Returning by Value vs Reference in C++
When should I return by value from a function, and when should I return by reference?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant