Next: Example function: sum of Up: Introduction to User-defined functions Previous: Functions with parameters and

Functions that return values

One of the most useful forms of function is one that returns a value that is a function of its parameters. In this case the type given to the function is that of the value to be returned. Thus consider the function, previously considered, which given the co-ordinates of a point (x,y) will return its distance from the origin:

float distance(float x, float y)
      // Returns the distance of (x, y) from origin
  {
    float dist;  //local variable
    dist = sqrt(x * x + y * y);
    return dist;
  }
Download program.

The function prototype for this function is:

float distance(float, float); // function prototype

This function introduces several new features. Note the following:

When the function is called the formal parameters x and y are replaced by actual parameters of type float and in the same order, i.e. the x co-ordinate first. Since the function returns a value it can only be used in an expression.

Hence the following examples of the use of the above function in a program in which it is declared:

float a, b, c, d, x, y;
a = 3.0;
b = 4.4;
c = 5.1;
d = 2.6;

x = distance(a, b);
y = distance(c, d);

if (distance(4.1, 6.7) > distance(x, y))
   cout << "Message 1" << endl;

A function may have several return statements. This is illustrated in the following function which implements the algorithm for evaluating the square root previously considered.

float mysqrt(float x)
      // Function returns square root of x.
      // If x is negative it returns zero.
  {
    const float tol = 1.0e-7;  // 7 significant figures
    float xold, xnew;          // local variables
    if (x <= 0.0)
      return 0.0;             // covers -ve and zero case
    else
      {
        xold = x;               // x as first approx
        xnew = 0.5 * (xold + x / xold); // better approx
        while (fabs((xold-xnew)/xnew) > tol)
          {
            xold = xnew;
            xnew = 0.5 * (xold + x / xold);
          }
        return xnew;   // must return float value
       }
  } // end mysqrt
Download program.

If the function has type void then it must not return a value. If a void function does return a value then most compilers will issue some form of warning message that a return value is not expected.



Next: Example function: sum of Up: Introduction to User-defined functions Previous: Functions with parameters and