5.6. Program Design with functions

  • A function is used to divide a program into logical units or sub-parts. Each function should perform one small task relative to the larger task at hand. Repeated calls to the same function provides a way to execute the same code more than once.

  • Functions are a natural outcome of a top-down design of the program. Functions provide a way of simplifying the program by forming abstractions of the problem at various levels of detail. At the highest level of the program (main), we look at the big picture problem. Here, we generally call functions that each perform a major sub-part of the problem. In main() we look at the big picture of the program.

    At the next lower level, we get a little more detailed, but will often call other functions to perform very specific tasks. At this level, we start to sort out some of the finer details of the implementation of the program.

    We will also write some functions which perform a very specific task. These functions may be called from several parts of the program. Here we focus our attention on the details of how to implement a task which although important, may have little to do with the big picture at hand.

  • Knowing when to divide a program into separate functions versus keeping the code together is some what an art form which is best perfected by practice. Two questions will help with the design decisions.

    1. Does the code need to be executed more than once, especially with different values?
    2. Does the code provide a specific task? If so, putting it in a function may help to draw attention to the task and thus improve the clarity of the program.

5.6.1. An example

Sometimes, we write a function that is basically a wrapper around another function. For example, the C library provides a random number generator, rand(). The rand() function returns a random number which is between zero and RAND_MAX (a very large number). If our program needs random numbers that is within a defined limited range, we might be able make use of the following function.

#include <stdio.h>
#include <stdlib.h>

int Rand(int, int);

int main( void )
{
   int r, i;
   int max, min;

   min = 35;
   max = 0;
   for( i = 0 ; i < 10000; i++ ) {
      r = Rand( 0, 35 );
      if ( r < min ) min = r;
      if ( r > max ) max = r;
   }
   printf( "\nmin: %d, max: %d\n", min,max );
   return 0;
}

/*
*  A function to return a random number in a set range.
*/
int Rand( int min, int max )
{
   int range;

   if( max == min )
      return( max );

   range = ((max > min) ? (max - min) : (min - max)) + 1;

   return( min + (int)((float)rand()*range/(RAND_MAX+1)));
}