Sign in to follow this  
Marz

decreasing a var in a function

Recommended Posts

Marz    150
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 this post


Link to post
Share on other sites
ZX_SA    128
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 this post


Link to post
Share on other sites
Cygon    1219
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 this post


Link to post
Share on other sites
cignox1    735
Quote:

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
}


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
}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this