C++ functions that return values

C++ functions that return values

C++ functions that return values – One of the most useful forms of function is the one that returns a value. In this case the type given to the function is that of the value to be returned. Thus consider the function, to which the co-ordinates of a point(x,y) are supplied as the input and returns the distance of the point from the origin as the output.

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;
}

The function prototype for this function is:

Float distance (float, float); //function prototype
This function introduces several new features such as:

  • The function has been given the type float because it is going to return a float value.
  • The parameter-list now has two parameters, namely, x and y. Each parameter is declared by giving its type and comma separates name and successive parameter declarations.
  • A local variable dist has been declared to temporarily hold the calculated distance.
  • Because this function returns a value it includes a return statement, which returns the value. In a statement return value the value may be a constant, a variable or an expression. Hence the use of local variable dist was not essential since the return statement could have been written.
  • return sqrt(x * x +y*y);

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 C++ 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 mysqurt(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;  // locat variables
If(x <=0.0)
return 0.0;   //covers –ve and zero case
else
{
xold=x;      // x as first approx
x new = 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

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 accepted.

Leave a Reply

Your email address will not be published.