Next: Example Program: Invoice Processing Up: Further User-defined functions in Previous: Further User-defined functions in

Call-by-reference parameters

Values cannot be returned to the calling program via call-by-value parameters because the function only operates on a copy of the value of the parameters, not on the actual parameter itself. If it is required to return a value by a parameter then the address of the actual parameter used in the function call must be passed to the function. The function can then use this address to access the actual parameter in its own space in the calling program and change it if required. Thus what we are passing is a reference to the parameter. Hence call-by-reference parameters.

To indicate that a parameter is called by reference an & is placed after the type in the parameter list. Any change that is made to that parameter in the function body will then be reflected in its value in the calling program.

For example consider the following function to evaluate the solution of a quadratic equation:

// solves the quadratic equation a*x*x+b*x+c = 0.
// If the roots are real then the roots are
// returned in two parameters root1 and root2 and
// the function returns true, if they are complex
// then the function returns false.

bool quadsolve(float a,        // IN coefficient
               float b,        // IN coefficient
               float c,        // IN coefficient
               float& root1,   // OUT root
               float& root2)   // OUT root

  {
    float disc;      // local variable
    disc = b * b - 4 * a * c;
    if (disc < 0.0)
      return false;
    else
      {
        root1 = (-b + sqrt(disc))/(2 * a);
        root2 = (-b - sqrt(disc))/(2 * a);
        return true;
      }
  }
Download program.

Note that the roots, which are output parameters, have been declared to be reference parameters, while the coefficients are input parameters and hence are declared to be value parameters. The function prototype would have the following form:

int quadsolve(float, float, float, float&, float&);

This might be called in a program as follows:

float c1, c2, c3;
float r1, r2;
      .
      .
if (quadsolve(c1, c2, c3, r1, r2))
    cout << "Roots are " << r1 << " and " << r2 << endl;
else
    cout << "Complex Roots" << endl;
Download program.

Note how the return value has been used to discriminate between the situation where the roots are real and are found in the two output parameters and the case where the roots are complex and no values for the roots are returned.



Next: Example Program: Invoice Processing Up: Further User-defined functions in Previous: Further User-defined functions in