References are also sometimes used as parameters to functions. In this case, the
initialisation of the reference takes place when the actual parameters are copied into the
formal parameters, e.g.
#include <iostream.h>
#include <iomanip.h>
void fred(int i, int& j)
{
i = 3; // assign to a local copy of the
// first argument
j = 4; // modify variable in caller's scope
}
int main()
{
int a = 1, b = 2;
cout << setw(2) << a << b; // prints "1 2"
fred(a,b);
cout << setw(2) << a << b; // prints "1 4"
return 0;
}
Needless to say, references are actually implemented using pointers!
initialisation of the reference takes place when the actual parameters are copied into the
formal parameters, e.g.
#include <iostream.h>
#include <iomanip.h>
void fred(int i, int& j)
{
i = 3; // assign to a local copy of the
// first argument
j = 4; // modify variable in caller's scope
}
int main()
{
int a = 1, b = 2;
cout << setw(2) << a << b; // prints "1 2"
fred(a,b);
cout << setw(2) << a << b; // prints "1 4"
return 0;
}
Needless to say, references are actually implemented using pointers!
No comments:
Post a Comment