Activity 4-1 - Void Functions



So far, we have seen and used functions that return a value. Sometimes, it is convenient to create a function that carries out some activities but does not return a value to the calling function. Such a function may perform some calculations and display the result.  A good example of such a function is one that displays a set of instructions on the screen regarding how a program works.  Including the instruction function will improve the program.  If we put the extra information in the main function, we will clutter up the main and make it longer and more tedious to read. Instead, we can put the user instructions in a separate function named (what else?) "instructions". This function has a name (instructions), it does not have any arguments, it is of type void, i.e., it does not return any value.

Here is an example for the instruction function:
void instructions( )
{
     cout << "This program will compute the total cost of purchases made by a user \n";
     cout << "The program will apply a 5% tax to the total cost of items minus any discount. \n";
     cout << "The input to this program is the cost of each item, quantity, and the discount. \n";
     cout << "The output is the grand total cost of all items together. \n";
}

Note that since the function is of type void, no return statement is used.  However, a void function may have a return statement, but it will return nothing, i.e.,

return;

may be used in a void function as well.  The inclusion of return;  in a void function may be inevitable when one wants to exit the function upon reaching a specific condition.  For example:

if( cost_per_item <=0)
    return;
else
   do something  .....

Exercise 4.1
Another example of a void function is a function that takes a real value and displays it with a specific number of decimal points.

void display_it(double x, int precision)
{
      cout.setf(ios::fixed);
      cout.setf(ios::showpoint);
      cout.precision(precision);
      cout << x << endl;
}

Use overloading to write a function that displays two real values with a specific precision.