Game Development Reference
In-Depth Information
Return Values
Functions can return values to the calling code to be stored within variables or passed as
parameters to other functions. Listing 5-3 shows how to return a value from the function.
Listing 5-3. Returning Values from Functions
#include <iostream>
using namespace std;
int ReturnSum(int valueA, int valueB)
{
return valueA + valueB;
}
int _tmain(int argc, _TCHAR* argv[])
{
int sum = ReturnSum(3, 6);
cout << sum << endl;
return 0;
}
The function ReturnSum has a new return type in its signature: It now reads int rather than void .
Inside the function you now see that we use the return keyword to return the value from the +
operator. We store the returned value from ReturnSum into the variable sum , which is then used with
cout to print the result 9 to the console.
Any of the built-in types can be used as parameter or return types. The functions we have looked at
in Listings 5-1, 5-2, and 5-3 all pass and return their function by value. This means that the compiler
will make a copy of the values when they are being passed to or from the function. Sometimes we
would like to be able to alter the values that come into our function so that the calling code can
access the new values, and we can do this by passing in pointers.
Passing by Pointer
Listing 5-4 alters our previous example to pass the result of our sum back to the calling code using a
pointer.
Listing 5-4. Passing by Pointer
#include <iostream>
using namespace std;
void ReturnSum(int inValueA, int inValueB, int* outValue)
{
*outValue = inValueA + inValueB;
}
 
Search WWH ::




Custom Search