Reputation: 97
I am very confused by using pointers. In the code below, if I set currentYear = 2010, I expect the value of 2010 to be assigned to initYear. But when I debug it, in the first line of the code, inityear = 2009. In the last line of the code, initYear also equals 2009, and currentYear = 2010.
Anyone can explain why this happens, and how I can make initYear to be 2010 when currentYear is 2010? Thanks.
Here is the code:
int initYear = pEnvContext->currentYear;
for ( int i=0; i < m_numberOfRuns; i++ )
{
UpdateMonteCarloInput(pEnvContext,i);
pEnvContext->run=i;
pEnvContext->currentYear=initYear;
Upvotes: 0
Views: 64
Reputation: 23031
Use a reference:
int& initYear = pEnvContext->currentYear;
Now initYear
is basically another way to access the value of currentYear
. See here to learn more about references.
Upvotes: 2
Reputation: 1648
This line:
int initYear = pEnvContext->currentYear;
copies the value stored in pEnvContext->currentYear to the initYear variable; so, no matter what will happen with currentYear, initYear contains its own copy.
If you want to have a reference to the currentYear and you want it to be updated when the currentYear is updated, use a reference (as Danvil stated before).
Upvotes: 0