#include <iostream>
using namespace std;
/*
* Swap function (same as before, but with double).
*/
void swap(double &a, double &b)
{
int t = a;
a = b;
b = t;
}
/*
* This function uses reference paramters to return several
* calculated values. Takes x and y, and returns their absolute difference,
* mean and sum of squares.
*/
void stats(double x, double y, double &absdif, double &mean, double &sumsqr)
{
if(x > y) swap(x, y);
absdif = y - x;
mean = (x + y) / 2.0;
sumsqr = x*x + y*y;
}
/*
* Test driver
*/
int main()
{
// First example.
double c = 4.56;
double d = -3.45;
double absdif, mean, ss;
stats(c, d, absdif, mean, ss);
cout << c << " " << d << " " << absdif << " " <<
mean << " " << ss << endl;
// Second example
stats(22.0, 41.5, absdif, mean, ss);
cout << absdif << " " << mean << " " << ss << endl;
}
Another use of reference parameters is to effectively
return multiple values from a function by assigning them
to parameters. The stats function has five parameters,
two of which are essentially inputs and three are outputs.
Some languages allow you to declare parameters input and
output, but in C++ you can only comment it.