FAQ 11.01 What is a reference?

A reference is an alias, an alternate name for an object. References are frequently used for passing parameters by reference (pass-by-reference; see FAQ 2.09). In the following example, function swap() receives its parameters by non-const reference since it needs to change the values of the caller's actual parameters, in this case main()'s i and j.

 #include <iostream> using namespace std; void swap(int& x, int& y) throw() {   int temp = x;   x = y;   y = temp; } int main() {   int i = 5;   int j = 7;   cout << "before: i=" << i << ", j=" << j << '\n';   swap(i, j);   cout << "after:  i=" << i << ", j=" << j << '\n'; } 

Here x and y become aliases for main()'s i and j, respectively. The effect is similar to the C-style pass-by-pointer, but without the caller having to take the address of the parameters and without the callee having to dereference pointers. That is, it would be illegal to change swap(i, j) in main() to swap(&i, &j), and it would be illegal to change x = y in swap() to *x = *y.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net