< previous page page_543 next page >

Page 543
int Factorial( int );
float CargoMoment( int );
C++ allows a function return value to be of any data typebuilt-in or userdefinedexcept an array (a data type we introduce in the next chapter).
In the last section, we wrote a Switch statement to convert a pair of char values into a value of type Animals. Let's write a value-returning function that performs this task. Notice how the function heading declares the data type of the return value to be Animals.
Animals CharToAnimal( /* in */ char ch1,
                      /* in */ char ch2 )
{
    switch (ch1)
    {
        case R : if (ch2 == o)
                       return RODENT;
                   else
                       return REPTILE;
        case C : return CAT;
        case D : return DOG;
        case B : if (ch2 == i)
                       return BIRD;
                   else
                       return BOVINE;
        case H : return HORSE;
        default :  return SHEEP;
    }
}
In this function, why didn't we include a break statement after each case alternative? Because when each alternative executes a return statement, control immediately exits the function. It's not possible for control to fall through to the next alternative.
Here is a sample of code that calls the CharToAnimal function:
enum Animals {RODENT, CAT, DOG, BIRD, REPTILE, HORSE, BOVINE, SHEEP};

Animals CharToAnimal( char, char );
  .
  .
  .
int main()
{
    Animals inPatient;
    Animals outPatient;
    char    char1;

 
< previous page page_543 next page >