next up previous
Next: About this document ... Up: Getting More Out of Previous: Variable Scope

Function Arguments as References

In C++, references make it easier to handle output arguments.

// The definition of the subprogram
void f_and_df(double x, double &fr, double &dfdxr){
   fr = 4*x - cos(x);
   dfdxr = 4 + sin(x);
}

In the main program we call the subprogram this way:

int main(){
     double x, f, dfdx;
     ...
     // The calling statement:
     f_and_df(x, f, dfdx);
     pnew = p - f/dfdx;
     ...
}

Notice several new features here: If we didn't know the subprogram was treating the second and third arguments as references, we would think all arguments were being passed by value. The distinction comes only if we try to pass an expression where a reference is expected, as in f_and_f(x,2*f,dfdx + 1.);. This is not permitted for nonconstant reference arguments and certainly doesn't make sense if the second and third arguments are ``output'' values.


next up previous
Next: About this document ... Up: Getting More Out of Previous: Variable Scope
Carleton DeTar 2009-09-23