A reference is an alias for another variable
Pass-By-Reference
C++ allows you to use real pass-by-reference
Declare Reference
int main(int argc, char** argv) {
int x = 5, y = 10;
int& z = x; // binds the name "z" to x
z += 1; // sets z (and x) to 6
x += 1; // sets x (and z) to 7
z = y; // sets z (and x) to the value of y
z += 1; // sets z (and x) to 11
return EXIT_SUCCESS;
}
Pass By Reference
void swap(int& x, int& y) {
int tmp = x;
x = y;
y = tmp;
}
int main(int argc, char** argv) {
int a = 5, b = 10;
swap(a, b);
cout << "a: " << a << "; b: " << b << endl; // a and b are swapped
return EXIT_SUCCESS;
}
Memory Diagram
