59

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?

I mean something like that won't work, right?

int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;

If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.

Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.

Waqar
  • 8,558
  • 4
  • 35
  • 43
Blake
  • 842
  • 6
  • 16
  • 1
    Why do you want to do that? – Robert Andrzejuk Mar 28 '19 at 17:18
  • 4
    Right, that won't work. That's a spreadsheet thing. – Pete Becker Mar 28 '19 at 17:22
  • 3
    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere. – Blake Mar 28 '19 at 17:32
  • 23
    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it. – Onyz Mar 28 '19 at 18:35
  • 47
    That's called a "function." – ApproachingDarknessFish Mar 28 '19 at 22:58
  • You want to learn how to use [_expression trees_](https://www.geeksforgeeks.org/expression-tree/). – Nat Mar 29 '19 at 05:16
  • 2
    Related: https://stackoverflow.com/questions/414243/lazy-evaluation-in-c – Bardi Harborow Mar 29 '19 at 06:15
  • Referring to @Onyz's comment: Yet another approach is not updating on calling the getter (for z in your example), but updating on modifying the base values (i. e. in the setters, in your example for x and y). – Aconcagua Mar 29 '19 at 09:31
  • 2
    @Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to `mpz_class`, at which point the expression tree is evaluated to produce the final result. It allows expressions like `a += b * c;` to collapse to (ignoring accessor functions involved) `mpz_addmul(a, b, c)` (which is an optimized one-operation version of the above), rather than creating a temporary `t` and do `mpz_mul(t, b, c)` followed by `mpz_add(a, a, t)` followed by cleaning `t`. It's a production version of [this](https://stackoverflow.com/a/414260/364696). – ShadowRanger Mar 29 '19 at 16:38
  • 5
    Surely this is a bit of an XY-problem? – Carmeister Mar 29 '19 at 18:25
  • [What is the XY problem?](https://meta.stackexchange.com/q/66377/230282) – phuclv Mar 30 '19 at 08:28
  • 2
    You might like to read up on [reactive programming](https://en.wikipedia.org/wiki/Reactive_programming). There is a C++ reactive programming framework [here](https://github.com/schlangster/cpp.react) which might be useful – Steve Lorimer Apr 02 '19 at 19:38
  • @Onyz I think your comment is the closest to suggesting a class. I obviously support this: https://stackoverflow.com/a/55422936/2642059 As C++ provides classes explicitly for the computational association of members. I just wanted to spell that out here to ensure that there was at least a comment suggesting this mechanic. – Jonathan Mee Apr 04 '19 at 12:50

12 Answers12

59

Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.


You mean something like this:

class Z
{
    int& x;
    int& y;
public:
    Z(int& x, int& y) : x(x), y(y) { }
    operator int() { return x + y; }
};

The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:

int x, y;
Z z(x, y);
std::cin >> x >> y;
if(std::cin) // otherwise, IO error! (e. g. bad user input)
    std::cout << z << std::endl;

Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer. – Blake Mar 29 '19 at 14:42
  • 5
    @NayWunnaZaw: If it's a one-off usage, sure, use the `lambda`. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. [one of the operator wrappers](https://en.cppreference.com/w/cpp/utility/functional#Operator_function_objects) like `std::plus`) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a *pattern*, not merely a one-off trick. – ShadowRanger Mar 29 '19 at 16:43
  • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question. – Blake Mar 29 '19 at 18:21
  • 5
    @NayWunnaZaw: BTW, just to be clear: You realize lambdas *are* (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to `operator()`) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides `operator int` (so implicit conversion does the trick), where lambdas implicitly override `operator()` (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes. – ShadowRanger Mar 29 '19 at 19:16
  • This is my personal favourite kind of answer! – Ted Lyngmo Mar 30 '19 at 07:04
  • Please don't do that, ever. This kind of operator abuse may be good for showing off, but it kills readability. Just use a proper method, or `operator()` if you really have to shorten it, but don't disguise a function call as a variable access. – Frax Mar 31 '19 at 17:00
  • @Frax Even with all the answers here, I'm still not sure if I should use these or just do the function call whenever I need the `z`. Is there any *good practice* to suggest? – Blake Apr 01 '19 at 17:42
  • 1
    @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one... – Aconcagua Apr 01 '19 at 19:02
  • @MichaelD.Blake Yeah, it depends on application. What is important to note is that the choice depends not so much on what math you want to do, but rather on how to make your intentions clear to the reader (likely your future self), and make the code robust to the mistakes. This particular answer fails both conditions in most applications: (1) hidden function call makes the code harder to track and debug, (2) references in the class create non-obvious dangling pointer risk. If x and y pair is some well-define entity (a point?) then perhaps you should have a proper class holding them. – Frax Apr 03 '19 at 04:05
  • @MichaelD.Blake if your x and y are not well connected and exist only in some local scope (as in example code), then you should probably use function called explicitly on x and y (like `sum(x, y)`). If they are an entity, you should probably create a class/struct encapsulating, that fact, say `class Point {public: int x; int y; int ManhattanDistanceFromOrigin() { return x+y; } };`. Having a class enables you to use patterns like Observer. However, in most cases you won't need notification, or you can make it explicitly (like: `p.x = new_x; chart.recompute();`). – Frax Apr 03 '19 at 04:26
  • Importantly, this answer doesn't really address the underlying problem: how to make sure that all places using x+y will be updated when one of the values change. It just adds syntax sugar for writing x+y. – Frax Apr 03 '19 at 04:30
  • @Frax But that's the same with the lambdas or even macros, isn't it? – Aconcagua Apr 03 '19 at 16:13
  • @Aconcagua the last issue, with not addressing the underlying problem? Yep, lambdas and macros have the same problem, they are no or little more than a syntax sugar. And lambdas create similar risk in regard to dangling pointers. – Frax Apr 03 '19 at 19:26
  • Btw, I wrote my own answer, where I compare different approaches to the updating itself. – Frax Apr 03 '19 at 19:57
51

You can get close to this with by using a lambda in C++. Generally, when you set a variable like

int x;
int y;
int z{x + y};

z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.

If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like

int x;
int y;
auto z = [&](){ return x + y; };
cin >> x;
cin >> y;
cout << z();

and now z() will have the correct value instead of the uninitialized garbage that the original code had.

If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like

auto z = [&](){ static auto cache_x = x; 
                static auto cache_y = y; 
                static auto cache_result = x + y;
                if (x != cache_x || y != cache_y)
                {
                    cache_x = x; 
                    cache_y = y; 
                    cache_result = x + y;
                }
                return cache_result;
};
J.G.
  • 295
  • 2
  • 13
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
26

The closest you probably can get is to create a functor:

#include <iostream>

int main() {
    int x;
    int y;

    auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

    while(true) {
        std::cin >> x;
        std::cin >> y;
        std::cout << z() << "\n";
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
20

There are two chief techniques:

  1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).

  2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).

The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 2
    The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the [caching](https://stackoverflow.com/a/55402932/1312382) proposed by [NathanOliver](https://stackoverflow.com/users/4342498/nathanoliver)... – Aconcagua Mar 29 '19 at 09:27
  • 4
    @Aconcagua, amend that to: if calculations to be done are expensive *and reads are more frequent than updates*. Otherwise, we need to add a way to avoid computing values that don't get used. – Toby Speight Mar 29 '19 at 12:18
18

This sounds like the XY problem (pun intended).

From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.

Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".

Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:

class Player {
    std::vector<int> inventory;
    int cash;
public:
    int inventory_total();
    int net_worth();
}

//adds up total value of inventory
int Player::inventory_total() {
    int total = 0;
    for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
        total += *it;
    }
    return total;
}

//calculates net worth
int Player::net_worth() {
    //we are using inventory_total() as if it were a variable that automatically
    //holds the sum of the inventory values
    return inventory_total() + cash;
}


...


//we are using net_worth() as if it were a variable that automatically
//holds the sum of the cash and total holdings
std::cout << player1.net_worth();

I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.

That would be very annoying and error prone if you forgot to call the function somewhere.

In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Artelius
  • 48,337
  • 13
  • 89
  • 105
  • can you give me the pros and cons of using lambdas vs this? which would be better practice? – Blake Mar 29 '19 at 13:33
  • 1
    Yes, this is the (real) answer I would expect. Unfortunately, there is [FGITW](https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19533#19533) (I think it is a real problem). – Peter Mortensen Mar 30 '19 at 01:44
  • 1
    Maybe worth to mention: Such a separate `net_worth` variable would introduce *redundancy*. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an *optimisation* that only should get introduced *on need* (after analysis/profiling). – Aconcagua Apr 04 '19 at 06:19
8
  1. You create a function for that.
  2. You call the function with the appropriate arguments when you need the value.

int z(int x, int y)
{
   return (x + y);
}


int x;
int y;

// This does ot work
// int z{x + y};

cin >> x;
cin >> y;
cout << z(x, y);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    yes, i mean the only way to get z updated is to call that function everytime we change x and y values? – Blake Mar 28 '19 at 16:54
  • 1
    @NayWunnaZaw, you can avoid the repeated use of `x` and `y` by using a lambda function, as shown by Nathan but you still have to make the call. – R Sahu Mar 28 '19 at 16:57
  • 4
    @NayWunnaZaw To complete the issue: Even with my solution, there *is* a function call (to the cast operator!), just that it is implicit and not required explicitly... – Aconcagua Mar 28 '19 at 17:04
5

You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:

DEMO

int main()
{
    int x;
    int y;

    const auto z = [&x, &y](){ return x+y; };

    std::cin  >> x; // 1
    std::cin  >> y; // 2
    std::cout << z() << std::endl; // 3

    std::cin  >> x; // 3
    std::cin  >> y; // 4
    std::cout << z() << std::endl; // 7
}
Hiroki
  • 2,780
  • 3
  • 12
  • 26
  • 2
    Don't use parentheses around return values – `return` is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being `decltype(auto)`). – Aconcagua Mar 28 '19 at 16:53
  • Why downvoted ? At least I posted my answer [faster](https://stackoverflow.com/questions/55402807/how-to-make-a-variable-always-equal-to-the-result-of-some-calculations?answertab=oldest#tab-top) than Ted with my tested code. Hmm... :) – Hiroki Mar 29 '19 at 09:30
  • 1
    Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they *were* the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...) – Aconcagua Mar 29 '19 at 09:44
  • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words. – Hiroki Mar 29 '19 at 20:36
5

So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables. I would suggest doing that via class:

class foo {
    int x;
    int y;
    int z;
    void calculate() { z = (x + y) / 2; }
    friend istream& operator >>(istream& lhs, foo& rhs);
public:
    void set_x(const int param) {
        x = param;
        calculate();
    }
    int get_x() const { return x; }
    void set_y(const int param) {
        y = param;
        calculate();
    }
    int get_y() const { return y; }
    int get_z() const { return z; }
};

istream& operator >>(istream& lhs, foo& rhs) {
    lhs >> rhs.x >> rhs.y;
    rhs.calculate();
    return lhs;
}

This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:

class foo {
    int x;
    int y;
    int z;
    bool dirty;
    void calculate() { z = (x + y) / 2; }
    friend istream& operator >>(istream& lhs, foo& rhs);
public:
    void set_x(const int param) {
        x = param;
        dirty = true;
    }
    int get_x() const { return x; }
    void set_y(const int param) {
        y = param;
        dirty = true;
    }
    int get_y() const { return y; }
    int get_z() const { 
        if(dirty) {
            calculate();
        }
        return z;
    }
};

istream& operator >>(istream& lhs, foo& rhs) {
    lhs >> rhs.x >> rhs.y;
    rhs.dirty = true;
    return lhs;
}

Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:

foo xyz;

cin >> xyz;
cout << xyz.get_z();
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++? – Blake Mar 29 '19 at 18:47
  • 2
    @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple `foo` which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here. – Jonathan Mee Mar 29 '19 at 18:58
  • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there. – Blake Mar 29 '19 at 19:10
  • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding `z` once. Is that where you're at? – Jonathan Mee Apr 04 '19 at 12:38
3

You could write a class that encapsulates its state to update either when mutated or return the right result when requested :

#include <iostream>

template<typename T, typename U, typename V>
class DynamicCalc
{
public:
    DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
        _func(func)
      , _memberOne(memberOne)
      , _memberTwo(memberTwo)
    {

    }

    void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
    void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
    auto Retrieve() { return _func(_memberOne, _memberTwo); }

    U GetMemberOne() { return _memberOne; }
    V GetMemberTwo() { return _memberTwo; }

private: 
    T _func;

    U _memberOne;
    V _memberTwo;
};

int main() {

    auto func = [](int x, int y) {
        return x + y;
    };
    DynamicCalc<decltype(func), int, int> c(func, 3, 5);

    c.SetMemberOne(5);
    std::cout << c.Retrieve();
}

In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.

George
  • 2,101
  • 1
  • 13
  • 27
3

You can get what you're asking for by using macros:

{
    int x, y;
#define z (x + y)
    /* use x, y, z */
#undef z
}

The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.

Although a class with a custom operator int would work in a lot of cases ... hmm.

o11c
  • 15,265
  • 4
  • 50
  • 75
  • 1
    Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach. – Artelius Mar 29 '19 at 07:13
3

What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.

0

Ok, let me at last write the right and only true answer to your stated question:

You can't.

You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.

So what can be done?

As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.

Depending on a use case, you may:

  • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.

    For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.

  • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.

  • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.

  • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.

Community
  • 1
  • 1
Frax
  • 5,015
  • 2
  • 17
  • 19