Recalling the previous value of a variable?

Viewed 1364

I'm a little new to c++ and I hate running across situations where I need to store a previous value in another variable. So my question is, can I make a variable in a sense store two values. I wish I could have the ability to recall previously stored values and use them in other functions.

ex) Current way

int x1 = 5;
int x2 = x1 + 5;
int diff = x2 - x1;

What I want to do

int x = 5;
x = x + 5;
int diff = x - old_x;
1 Answers

Here's a minimal class that works for your particular use case:

struct Int {
    int val = 0, old_val = 0;
    Int(int i) : val(i) {}
    operator int() { return val; }
    void operator=(int i) { old_val = std::exchange(val, i); }
    int old() { return old_val; }
};

and you could use it like this:

Int x = 5;
x = x + 7;
int diff = x - x.old();  // diff is 7

Here's a demo.

Note that this class is minimal, and in practice, you would want to make Int model an int as closely as possible, with only the additional property of remembering the previous value.

Related