Public Group

# decreasing a var in a function

This topic is 4849 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have spent countelss hours trying to get this problem solved. drain = -(top_speed/10) I need Stamina to drop by drain amount everytime the function is called. I tried making a static var called vEnergy = stamina_scocre. then I set vEnergy = vEnergy + drain. so say stamina is 100 and drain is -8. but it doesn't work I need it to be 92 first call then 84 and so on, but for the life of me it won't go. Please help if ya can:)

##### Share on other sites
It would help if you tell us what it IS doing. Maybe some code as well.

I can think of two possible causes if your variable isn't going down: (1) You're constantly overwriting its value with the max value, or (2) you're not calling the function that is supposed to decrease it often enough.

##### Share on other sites
3. Maybe you're forgetting that C and C++, by default, have copy-by-value semantics, that is

void decrease(int x) {  x -= 10;}int main() {  int x = 100;  decrese(x);  // x is still 100 because only a copy was passed to the function}

Instead the variable should be passed by reference in order to be able to modify it within a function
void decrease(int &x /* <- reference */) {  x -= 10;}int main() {  int x = 100;  decrease(x);  // Now, x is 90}

-Markus-

##### Share on other sites
Quote:
 Instead the variable should be passed by reference in order to be able to modify it within a functionvoid decrease(int &x /* <- reference */) { x -= 10;}int main() { int x = 100; decrease(x); // Now, x is 90}

If you are programming in C (instead of c++) and this is the problem (chance are it is), then use pointers:
void decrease(int *x /* <- address*/) {  *x -= 10;}int main() {  int x = 100;  decrease(&x);  // Now, x is 90}

• 10
• 17
• 9
• 14
• 41
• ### Forum Statistics

• Total Topics
631073
• Total Posts
2997754
×