← Back to C++ Course | Chapter 5: Functions | Lesson 4 of 13

C++ Passing by Reference

Declaring a function parameter with & makes it a reference to the caller's argument, letting the function modify the original variable directly instead of working on a copy.

Pass by Value vs Pass by Reference

By default, C++ passes arguments by value, giving the function its own copy, but adding & to a parameter's type makes it a reference, letting the function operate on the caller's original variable instead.

Example: Pass by Value vs Pass by Reference

cpp
#include <iostream>

void byValue(int x) { x = 99; }
void byReference(int &x) { x = 99; }

int main() {
	int a = 1, b = 1;
	byValue(a);
	byReference(b);
	std::cout << "a=" << a << " b=" << b << std::endl;
	return 0;
}

Modifying the Caller's Variable

A reference parameter shares the same memory as the caller's argument, so any assignment made to the parameter inside the function immediately changes the value the caller sees.

Example: Modifying the Caller's Variable

cpp
#include <iostream>

void reset(int &score) {
	score = 0;
}

int main() {
	int score = 50;
	reset(score);
	std::cout << score << std::endl;
	return 0;
}

Returning Multiple Values via Reference Parameters

Since a function can only return one value directly, reference parameters are a common technique for a function to effectively hand back several results to its caller.

Example: Returning Multiple Values via Reference Parameters

cpp
#include <iostream>

void minMax(int a, int b, int &minVal, int &maxVal) {
	if (a < b) { minVal = a; maxVal = b; }
	else { minVal = b; maxVal = a; }
}

int main() {
	int lo, hi;
	minMax(8, 3, lo, hi);
	std::cout << "min=" << lo << " max=" << hi << std::endl;
	return 0;
}

Passing Large Objects by Reference for Performance

Passing a large object like a big string or a struct by reference avoids the cost of copying it entirely, since the function receives a reference to the existing data instead of a duplicate.

Example: Passing Large Objects by Reference for Performance

cpp
#include <iostream>
#include <string>

void printLength(const std::string &text) {
	std::cout << "Length: " << text.length() << std::endl;
}

int main() {
	std::string bigText = "A long string that would be costly to copy";
	printLength(bigText);
	return 0;
}

const Reference Parameters

Combining const with a reference parameter, written as const Type&, passes the argument efficiently without copying it while also preventing the function from accidentally modifying the caller's original data.

Example: const Reference Parameters

cpp
#include <iostream>
#include <string>

void show(const std::string &name) {
	std::cout << "Hello, " << name << std::endl;
	// name = "Changed"; // compile error: cannot modify a const reference
}

int main() {
	show("Alex");
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.