cpp / beginner
Snippet
Pass by Value vs Pass by Reference
When passing arguments to functions, C++ creates a copy by default (pass by value). Using the ampersand (&) in the parameter declaration creates a reference to the original variable (pass by reference). Pass by value protects the original from changes but uses more memory. Pass by reference allows modification but directly affects the caller's variable.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>void byValue(int x) {x = x + 10;}void byReference(int& x) {x = x + 10;}int main() {int a = 5;int b = 5;byValue(a);std::cout << "byValue result: " << a << std::endl;byReference(b);std::cout << "byReference result: " << b << std::endl;return 0;}
Breakdown
1
void byValue(int x)
Parameter x is a copy of the argument
2
void byReference(int& x)
Parameter x is a reference to original
3
a stays 5, b becomes 15
Demonstrates the key difference