Value Categories and References
Swap By Reference
Functions can take references when they need to update caller-owned values directly.
reference parameter
A non-const reference parameter allows a function to update the caller's variable.
swap
Swapping through reference parameters changes both variables outside the function.
Swap By Reference
swap_by_reference.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
void swap_values(int& left, int& right) {
int saved = left;
left = right;
right = saved;
}
int main() {
int first = 4;
int second = 9;
swap_values(first, second);
std::cout << "first=" << first << std::endl;
std::cout << "second=" << second << std::endl;
return 0;
}
#include <iostream>
void swap_values(int& left, int& right) {
int saved = left;
left = right;
right = saved;
}
int main() {
int first = 1;
int second = 9;
swap_values(first, second);
std::cout << "first=" << first << std::endl;
std::cout << "second=" << second << std::endl;
return 0;
}
#include <iostream>
void swap_values(int& left, int& right) {
int saved = left;
left = right;
right = saved;
}
int main() {
int first = 10;
int second = 9;
swap_values(first, second);
std::cout << "first=" << first << std::endl;
std::cout << "second=" << second << std::endl;
return 0;
}
first ← 4, second ← 9
9int main() {10 int first→ 4 = 4; //@first=1, 1011 int second→ 9 = 9;1213 swap_values(first4, second9);saved ← 4, left ← 9, right ← 4
3void swap_values(int& left4, int& right9) {4 int saved→ 4 = left4;5 left→ 9 = right9;6 right→ 4 = saved4;7}first ← 9, second ← 4
13 swap_values(first→ 9, second→ 4);1415 std::cout << "first=" << first9 << std::endl;16 std::cout << "second=" << second4 << std::endl;17 return 0;18}outputfirst=9 second=4
first ← 1, second ← 9
9int main() {10 int first→ 1 = 1;11 int second→ 9 = 9;1213 swap_values(first1, second9);saved ← 1, left ← 9, right ← 1
3void swap_values(int& left1, int& right9) {4 int saved→ 1 = left1;5 left→ 9 = right9;6 right→ 1 = saved1;7}first ← 9, second ← 1
13 swap_values(first→ 9, second→ 1);1415 std::cout << "first=" << first9 << std::endl;16 std::cout << "second=" << second1 << std::endl;17 return 0;18}outputfirst=9 second=1
first ← 10, second ← 9
9int main() {10 int first→ 10 = 10;11 int second→ 9 = 9;1213 swap_values(first10, second9);saved ← 10, left ← 9, right ← 10
3void swap_values(int& left10, int& right9) {4 int saved→ 10 = left10;5 left→ 9 = right9;6 right→ 10 = saved10;7}first ← 9, second ← 10
13 swap_values(first→ 9, second→ 10);1415 std::cout << "first=" << first9 << std::endl;16 std::cout << "second=" << second10 << std::endl;17 return 0;18}outputfirst=9 second=10