Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recalling the previous value of a variable?

Tags:

c++

c++17

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;
like image 312
TylerSingleton Avatar asked Jan 31 '26 03:01

TylerSingleton


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.

like image 89
cigien Avatar answered Feb 02 '26 20:02

cigien