RETURNING VALUES FROM A FUNCTION
All the example functions that you have created have returned a single value. Is it possible to return anything other than a single value? Well, not directly, but as I said earlier, the single value returned need not be a numeric value; it could also be an address, which provides the key to returning any amount of data. You simply use a pointer. Unfortunately, this also is where the pitfalls start, so you need to keep your wits about you for the adventure ahead.
Returning a Pointer
Returning a pointer value is easy. A pointer value is just an address, so if you want to return the address of some variable value, you can just write the following:
return &value; // Returning an address
As long as the function header and function prototype indicate the return type appropriately, you have no problem — or at least, no apparent problem. Assuming that the variable value is of type double, the prototype of a function called treble, which might contain the preceding return statement, could be as follows:
double* treble(double data);
I have defined the parameter list arbitrarily here.
So let’s look at a function that returns a pointer. It’s only fair that I warn you in advance — this function doesn’t work, but it is educational. Let’s assume that you need a function that returns a pointer to a memory location containing three times its argument value. Our first attempt to implement such a function might look like this:
// Function to treble a value - mark ...
Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.