Value Categories and References
Swap By Reference
Functions can take references when they need to update caller-owned values directly.
Swap By Reference
swap_by_reference.cpp
#include <iostream>
void swap_values(int& left, int& right) {
int saved = left;
left = right;
right = saved;
}
int main() {
int first = ;
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 = ;
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 = ;
int second = 9;
swap_values(first, second);
std::cout << "first=" << first << std::endl;
std::cout << "second=" << second << std::endl;
return 0;
}
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.