Game Development Reference
In-Depth Information
int _tmain(int argc, _TCHAR* argv[])
{
int sum = 0;
ReturnSum(3, 6, &sum);
cout << sum << endl;
return 0;
}
Listing 5-4 initializes the variable sum to contain the value 0. ReturnSum now does not return a
value; instead it takes a pointer to an int as its third parameter. When we call ReturnSum we pass
the address of sum using &sum . Inside ReturnSum we alter the value stored at the pointer using the
following line:
*outValue = inValueA + inValueB;
The pointer dereference operator is used to tell the compiler that we want to change the value stored
at the pointer and not the pointer itself. In Listing 5-4 this achieves the result of altering the value of
sum from 0 to 9.
Note Pointers can be set to not contain a value. This is achieved by assigning nullptr to them. We'll cover
nullptr in Chapter 6 when we look at flow control statements.
As well as being able to pass values by pointer, we can also pass them by reference.
Passing by Reference
When we pass by pointer we must explicitly dereference the pointer to be able to retrieve its value.
There's also a possibility that the pointer might not point to a valid memory address but instead be
assigned a nullptr . If we dereference a nullptr our program will crash. If we use a reference then
we do not have to deference to obtain the value, we do not have to worry about nullptr s and we do
not have to use the address of operator when passing the initial variable to the function. You can see
this in Listing 5-5.
Listing 5-5. Passing by Reference
#include <iostream>
using namespace std;
void ReturnSum(int inValueA, int inValueB, int& outValue)
{
outValue = inValueA + inValueB;
}
 
 
Search WWH ::




Custom Search