user2993453
user2993453

Reputation: 1

My function displays correct number, but doesn't add it to the variable

I'm new to coding and have decided to make a game for fun! I recently added a hunger feature, so I made a function in order to increase hunger, then check to see if it has reached 10 (game over). It displays the correct amount of hunger properly, however it doesn't store the correct hunger level into the hunger variable.

double addHunger(double hunger,int add)
{
hunger = hunger+add;
if (hunger >= 10)
{
    cout <<"\n\nGame over! You starved to death, havn't you heard of eating you moronic idiot?\n";
    exit(1);
}
else
{   
    cout <<"\n\nYou feel your stomach growl. Your hunger is now " <<hunger<<"\n\n";
}
} 

For example, the hunger is originally at 6, and when I implement this function and add 1 hunger it will state the hunger is now 7, but the actual amount is still 6 in the main body, meaning if you reduce your hunger by one, it will go down to 5 as opposed to 6. How can I fix this?

Upvotes: 0

Views: 24

Answers (2)

JDP
JDP

Reputation: 73

Primitive values such as doubles are copied when you call a function which uses them as arguments. That means that when you are inside the addHunger function, you only have access to a new copy of the hunger variable. Changing its value will not affect the value of the hunger variable back in the main function.

Upvotes: 0

Codecat
Codecat

Reputation: 2241

Make hunger a reference:

double addHunger(double &hunger,int add)

Upvotes: 1

Related Questions