<<== <= [table of contents] [search] [glossary] [feedback] => ==>>

[online C++ tutorial]Section 5: Functions

Section 5.4: Returning Values from Functions

At this point we have seen some examples of functions. Just like a parameter to a function, we can return just about anything from a function: a variable, an instance of an object, a pointer, and yes, even a function pointer. (Don't worry about these, I'll explain them later).

The keyword return specifies what a function should return and when it should end execution of the function and return a value. For instance, here's a function that picks an interest rate based on an account type. This is the same code used in section 4.2

float 
WhichInterestRate(int account_type)
{
   switch (account_value)
   {
    case 1:
      return 2.3;
      break;
    case 2:
      return 2.6;
      break;
    case 3:
      return 2.9;
      break;
    case 4:
      return 3.3;
      break;
    case 5:
      return 3.5;
      break;
    case 6:
      return 3.8;
      break;
    default:
      return = 0.0;
   }
   return 0.0;
}

The function will return a value as soon as it hits a return statement. I really don't need the break statements in the code, but I like to leave them in as leaving them out in other instances of using a switch statement can cause big problems (without the break statements once a switch has selected a case it will execute all the code for every case after that). Similarly the return 0.0 just before the function ends is not necessary, except so the compiler doesn't complain that I need a return statement at the end of the function. As soon as the first return statement is encountered the function returns that value and finishes executing.

The void return

What if you don't want to return anything from a function? Some languages make a distinction between a function and a procedure, where a procedure is just a function that doesn't return anything. In C++ there is a return type, void that means "this function doesn't return anything". For example, here's a function that takes three numbers and prints out messages associated with each of them. There is nothing for the function to return.

void PrintMessage(int a, int b, int c){
   cout << "The first number is " << a << endl;
   cout << "The second number is " << b << endl;
   cout << "The third number is " << c << endl;
};

<<== <= [table of contents] [search] [glossary] [feedback] => ==>>