Introduction to Functions

Passing Arguments by Value vs Reference in C++

What is the difference between passing function arguments by value and by reference?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved