Saturday, August 22, 2009

Function that returns a value

Functions seen so far don't have a return value, i.e. their return type is void. They can, however, have any data type as a return type. i.e. the function returns data back to where it was called. A function call evaluates a value that can be used as a parameter for other functions, as an operand of operators etc. A C++ function definition is as follows:

return_type function_name ()
{
     function_body
}

or if the function has parameters:

return_type function_name (formal_parameters)
{
     function_body
}

All the same rules and characteristics apply to function name and formal parameters as for void functions. The return type is in every function definition ( and declaration ) and is the type of the value the function returns. The return type defines where the function can be called. The return_type can be any data type.

The function body can be any sequence of executable statements. For example:

double area( double x, double y )
{
     double result = x*y;
     return result;
}

return result; is called a return statement. It terminates the function execution and indicates the value given as the result of the function to the caller. One return statement must always get executed. The syntax of the return statement:

return return_value;

return immediately terminates the execution of the function and the execution continues from where the function was called. The value of the return_value decides to which value the function evaluates in the expression where it was called. The return_value must be of the same type as the return_type of the function.

There can be more than one return statement on the function body. The execution returns from the function immediately when one of the return statements is executed.

double absoluteValue(double x)
{
     if ( x > 0 )
     {
          return x;
     }
     else
     {
          return -x;
     }
}

Also the execution of a void function can be terminated with return. It is just used without the return_value:

return;

Information is passed only into one direction between the caller and a function (caller -> function) when the function does not return a value. Information is passed into both directions between the caller and a function (caller <==> function) when the function returns a value. A function can return only one value at a time. void is in fact a datatype without a value (an "empty" data type). The same rules apply to the declaration and definition of all kinds of functions.


Previous post

Next post




No comments:

Post a Comment