C++ How to store a previous value of a variable and update it for comparasion?



So there is a variable sensor.value which ranges anywhere from 1 - 1000. How would I capture the sensor.value's number initially so i can compare it to its future value.

For instance say sensor.value is 5 I would want it to save that value for comparison then if it suddenly increased I want to perform an action.

Example ( this is for a game so the context is kind of fuzzy )
1
2
3
4
5
6
    if ((command == 1){
    static int sensorValue = sensor.value;
    if (sensor.value > sensorValue){
    peformactionblahblah
    }
    }

Im having a hard time getting it to reupdate the value for sensorValue though.
You could store the initial value in a variable named initial_value, and then store the later value in a variable named later_value, and compare those.

initial_value = sensor.value; // At the initial time
then, some time later
later_value = sensor.value; // store the changed, later sensor value
@Moshops

I was trying to do that before but I cant tell if its because of how the game work or if it is because how c++ works;

When ever I did that it would always make these equal to each other (not saving the initial value but writing over it)

 
initial_value = sensor.value;  (ex 5 = 5;, changes to 6=6 with it, making compassion not possible)


As sensor.value updated so would initial_value. This is why I tried to play around with static variables but now I cant seem to get it to reupdate its values for comparing again after the performed action.

Once it performs the action I would like it to to do this again.
 
static int sensorValue = sensor.value;

I understand I could do sensorValue = sensor.value; again but it doesnt update properly and ends up working incorrectly.


EDIT: i did get it to update the value properly with your help and others but now it just does the action i wanted it to perform improperly (like it performs too much for no reason) . My operators could be messed up hmm.

Last edited on
In C++, static doesn't mean not changing.
Topic archived. No new replies allowed.