Returning Values


Now that you've seen how to declare what your function is going to return, how do you actually return a variable? It's actually pretty easy. Anywhere in your function, just say "return" and then the name of your variable. For instance, say you had a function that returned the number of doritos you felt like eating, and inside the function you had a variable named "yum" you wanted it to return. You'd say:

return yum;

At that point, the function stops and that variable is returned. Be careful, this is unlike Pascal, where you could assign the value you would return and the function would keep going. For example, if you had the function say "return yum;", then had it print out "I hate doritos!", it would never get to the part where it prints that messages out. Here's a full example of a function that returns a value:

int number_of_doritos(void)
{
   int yum;

   yum = 523;      /* That's a lot of doritos! */

   return yum;     /* Returns the value in yum, stops the function */

   cout << "I hate doritos!" << endl; /* Nobody ever sees this */
}


Table of Contents

Procedures/Functions | Returning Values | Passing Variables | Using Functions
Function Overloading | Default Parameters | Exercises